]> Pileus Git - ~andy/gtk/blob - gtk/gtktextview.c
Introduce gtk_render_insertion_cursor
[~andy/gtk] / gtk / gtktextview.c
1 /* -*- Mode: C; c-file-style: "gnu"; tab-width: 8 -*- */
2 /* GTK - The GIMP Toolkit
3  * gtktextview.c Copyright (C) 2000 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /*
22  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
23  * file for a list of people on the GTK+ Team.  See the ChangeLog
24  * files for a list of changes.  These files are distributed with
25  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
26  */
27
28 #include "config.h"
29
30 #include <string.h>
31
32 #define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
33 #include "gtkbindings.h"
34 #include "gtkdnd.h"
35 #include "gtkimagemenuitem.h"
36 #include "gtkintl.h"
37 #include "gtkmain.h"
38 #include "gtkmarshalers.h"
39 #include "gtkmenu.h"
40 #include "gtkmenuitem.h"
41 #include "gtkseparatormenuitem.h"
42 #include "gtksettings.h"
43 #include "gtkselectionprivate.h"
44 #include "gtkstock.h"
45 #include "gtktextbufferrichtext.h"
46 #include "gtktextdisplay.h"
47 #include "gtktextview.h"
48 #include "gtkimmulticontext.h"
49 #include "gtkprivate.h"
50 #include "gtktextutil.h"
51 #include "gtkwidgetprivate.h"
52 #include "gtkwindow.h"
53 #include "gtkscrollable.h"
54 #include "gtktypebuiltins.h"
55
56 #include "a11y/gtktextviewaccessible.h"
57
58 /**
59  * SECTION:gtktextview
60  * @Short_description: Widget that displays a GtkTextBuffer
61  * @Title: GtkTextView
62  * @See_also: #GtkTextBuffer, #GtkTextIter
63  *
64  * You may wish to begin by reading the <link linkend="TextWidget">text widget
65  * conceptual overview</link> which gives an overview of all the objects and data
66  * types related to the text widget and how they work together.
67  */
68
69
70 /* How scrolling, validation, exposes, etc. work.
71  *
72  * The expose_event handler has the invariant that the onscreen lines
73  * have been validated.
74  *
75  * There are two ways that onscreen lines can become invalid. The first
76  * is to change which lines are onscreen. This happens when the value
77  * of a scroll adjustment changes. So the code path begins in
78  * gtk_text_view_value_changed() and goes like this:
79  *   - gdk_window_scroll() to reflect the new adjustment value
80  *   - validate the lines that were moved onscreen
81  *   - gdk_window_process_updates() to handle the exposes immediately
82  *
83  * The second way is that you get the "invalidated" signal from the layout,
84  * indicating that lines have become invalid. This code path begins in
85  * invalidated_handler() and goes like this:
86  *   - install high-priority idle which does the rest of the steps
87  *   - if a scroll is pending from scroll_to_mark(), do the scroll,
88  *     jumping to the gtk_text_view_value_changed() code path
89  *   - otherwise, validate the onscreen lines
90  *   - DO NOT process updates
91  *
92  * In both cases, validating the onscreen lines can trigger a scroll
93  * due to maintaining the first_para on the top of the screen.
94  * If validation triggers a scroll, we jump to the top of the code path
95  * for value_changed, and bail out of the current code path.
96  *
97  * Also, in size_allocate, if we invalidate some lines from changing
98  * the layout width, we need to go ahead and run the high-priority idle,
99  * because GTK sends exposes right after doing the size allocates without
100  * returning to the main loop. This is also why the high-priority idle
101  * is at a higher priority than resizing.
102  *
103  */
104
105 #if 0
106 #define DEBUG_VALIDATION_AND_SCROLLING
107 #endif
108
109 #ifdef DEBUG_VALIDATION_AND_SCROLLING
110 #define DV(x) (x)
111 #else
112 #define DV(x)
113 #endif
114
115 #define SCREEN_WIDTH(widget) text_window_get_width (GTK_TEXT_VIEW (widget)->priv->text_window)
116 #define SCREEN_HEIGHT(widget) text_window_get_height (GTK_TEXT_VIEW (widget)->priv->text_window)
117
118 #define SPACE_FOR_CURSOR 1
119
120 #define GTK_TEXT_VIEW_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GTK_TYPE_TEXT_VIEW, GtkTextViewPrivate))
121
122 typedef struct _GtkTextWindow GtkTextWindow;
123 typedef struct _GtkTextPendingScroll GtkTextPendingScroll;
124
125 struct _GtkTextViewPrivate 
126 {
127   GtkTextLayout *layout;
128   GtkTextBuffer *buffer;
129
130   guint blink_time;  /* time in msec the cursor has blinked since last user event */
131   guint im_spot_idle;
132   gchar *im_module;
133   GdkDevice *grab_device;
134   GdkDevice *dnd_device;
135
136   gulong selection_drag_handler;
137
138   GtkTextWindow *text_window;
139   GtkTextWindow *left_window;
140   GtkTextWindow *right_window;
141   GtkTextWindow *top_window;
142   GtkTextWindow *bottom_window;
143
144   GtkAdjustment *hadjustment;
145   GtkAdjustment *vadjustment;
146
147   gint xoffset;         /* Offsets between widget coordinates and buffer coordinates */
148   gint yoffset;
149   gint width;           /* Width and height of the buffer */
150   gint height;
151
152   /* This is used to monitor the overall size request 
153    * and decide whether we need to queue resizes when
154    * the buffer content changes. 
155    *
156    * FIXME: This could be done in a simpler way by 
157    * consulting the above width/height of the buffer + some
158    * padding values, however all of this request code needs
159    * to be changed to use GtkWidget     Iface and deserves
160    * more attention.
161    */
162   GtkRequisition cached_size_request;
163
164   /* The virtual cursor position is normally the same as the
165    * actual (strong) cursor position, except in two circumstances:
166    *
167    * a) When the cursor is moved vertically with the keyboard
168    * b) When the text view is scrolled with the keyboard
169    *
170    * In case a), virtual_cursor_x is preserved, but not virtual_cursor_y
171    * In case b), both virtual_cursor_x and virtual_cursor_y are preserved.
172    */
173   gint virtual_cursor_x;   /* -1 means use actual cursor position */
174   gint virtual_cursor_y;   /* -1 means use actual cursor position */
175
176   GtkTextMark *first_para_mark; /* Mark at the beginning of the first onscreen paragraph */
177   gint first_para_pixels;       /* Offset of top of screen in the first onscreen paragraph */
178
179   guint blink_timeout;
180   guint scroll_timeout;
181
182   guint first_validate_idle;        /* Idle to revalidate onscreen portion, runs before resize */
183   guint incremental_validate_idle;  /* Idle to revalidate offscreen portions, runs after redraw */
184
185   gint pending_place_cursor_button;
186
187   GtkTextMark *dnd_mark;
188
189   GtkIMContext *im_context;
190   GtkWidget *popup_menu;
191
192   gint drag_start_x;
193   gint drag_start_y;
194
195   GSList *children;
196
197   GtkTextPendingScroll *pending_scroll;
198
199   /* Default style settings */
200   gint pixels_above_lines;
201   gint pixels_below_lines;
202   gint pixels_inside_wrap;
203   GtkWrapMode wrap_mode;
204   GtkJustification justify;
205   gint left_margin;
206   gint right_margin;
207   gint indent;
208   PangoTabArray *tabs;
209   guint editable : 1;
210
211   guint overwrite_mode : 1;
212   guint cursor_visible : 1;
213
214   /* if we have reset the IM since the last character entered */
215   guint need_im_reset : 1;
216
217   guint accepts_tab : 1;
218
219   guint width_changed : 1;
220
221   /* debug flag - means that we've validated onscreen since the
222    * last "invalidate" signal from the layout
223    */
224   guint onscreen_validated : 1;
225
226   guint mouse_cursor_obscured : 1;
227
228   guint scroll_after_paste : 1;
229
230   /* GtkScrollablePolicy needs to be checked when
231    * driving the scrollable adjustment values */
232   guint hscroll_policy : 1;
233   guint vscroll_policy : 1;
234 };
235
236 struct _GtkTextPendingScroll
237 {
238   GtkTextMark   *mark;
239   gdouble        within_margin;
240   gboolean       use_align;
241   gdouble        xalign;
242   gdouble        yalign;
243 };
244
245 enum
246 {
247   POPULATE_POPUP,
248   MOVE_CURSOR,
249   PAGE_HORIZONTALLY,
250   SET_ANCHOR,
251   INSERT_AT_CURSOR,
252   DELETE_FROM_CURSOR,
253   BACKSPACE,
254   CUT_CLIPBOARD,
255   COPY_CLIPBOARD,
256   PASTE_CLIPBOARD,
257   TOGGLE_OVERWRITE,
258   MOVE_VIEWPORT,
259   SELECT_ALL,
260   TOGGLE_CURSOR_VISIBLE,
261   PREEDIT_CHANGED,
262   LAST_SIGNAL
263 };
264
265 enum
266 {
267   PROP_0,
268   PROP_PIXELS_ABOVE_LINES,
269   PROP_PIXELS_BELOW_LINES,
270   PROP_PIXELS_INSIDE_WRAP,
271   PROP_EDITABLE,
272   PROP_WRAP_MODE,
273   PROP_JUSTIFICATION,
274   PROP_LEFT_MARGIN,
275   PROP_RIGHT_MARGIN,
276   PROP_INDENT,
277   PROP_TABS,
278   PROP_CURSOR_VISIBLE,
279   PROP_BUFFER,
280   PROP_OVERWRITE,
281   PROP_ACCEPTS_TAB,
282   PROP_IM_MODULE,
283   PROP_HADJUSTMENT,
284   PROP_VADJUSTMENT,
285   PROP_HSCROLL_POLICY,
286   PROP_VSCROLL_POLICY
287 };
288
289 static void gtk_text_view_finalize             (GObject          *object);
290 static void gtk_text_view_set_property         (GObject         *object,
291                                                 guint            prop_id,
292                                                 const GValue    *value,
293                                                 GParamSpec      *pspec);
294 static void gtk_text_view_get_property         (GObject         *object,
295                                                 guint            prop_id,
296                                                 GValue          *value,
297                                                 GParamSpec      *pspec);
298 static void gtk_text_view_destroy              (GtkWidget        *widget);
299 static void gtk_text_view_size_request         (GtkWidget        *widget,
300                                                 GtkRequisition   *requisition);
301 static void gtk_text_view_get_preferred_width  (GtkWidget        *widget,
302                                                 gint             *minimum,
303                                                 gint             *natural);
304 static void gtk_text_view_get_preferred_height (GtkWidget        *widget,
305                                                 gint             *minimum,
306                                                 gint             *natural);
307 static void gtk_text_view_size_allocate        (GtkWidget        *widget,
308                                                 GtkAllocation    *allocation);
309 static void gtk_text_view_realize              (GtkWidget        *widget);
310 static void gtk_text_view_unrealize            (GtkWidget        *widget);
311 static void gtk_text_view_style_updated        (GtkWidget        *widget);
312 static void gtk_text_view_direction_changed    (GtkWidget        *widget,
313                                                 GtkTextDirection  previous_direction);
314 static void gtk_text_view_grab_notify          (GtkWidget        *widget,
315                                                 gboolean         was_grabbed);
316 static void gtk_text_view_state_flags_changed  (GtkWidget        *widget,
317                                                 GtkStateFlags     previous_state);
318
319 static gint gtk_text_view_event                (GtkWidget        *widget,
320                                                 GdkEvent         *event);
321 static gint gtk_text_view_key_press_event      (GtkWidget        *widget,
322                                                 GdkEventKey      *event);
323 static gint gtk_text_view_key_release_event    (GtkWidget        *widget,
324                                                 GdkEventKey      *event);
325 static gint gtk_text_view_button_press_event   (GtkWidget        *widget,
326                                                 GdkEventButton   *event);
327 static gint gtk_text_view_button_release_event (GtkWidget        *widget,
328                                                 GdkEventButton   *event);
329 static gint gtk_text_view_focus_in_event       (GtkWidget        *widget,
330                                                 GdkEventFocus    *event);
331 static gint gtk_text_view_focus_out_event      (GtkWidget        *widget,
332                                                 GdkEventFocus    *event);
333 static gint gtk_text_view_motion_event         (GtkWidget        *widget,
334                                                 GdkEventMotion   *event);
335 static gint gtk_text_view_draw                 (GtkWidget        *widget,
336                                                 cairo_t          *cr);
337 static void gtk_text_view_draw_focus           (GtkWidget        *widget,
338                                                 cairo_t          *cr);
339 static gboolean gtk_text_view_focus            (GtkWidget        *widget,
340                                                 GtkDirectionType  direction);
341 static void gtk_text_view_select_all           (GtkWidget        *widget,
342                                                 gboolean          select);
343
344
345 /* Source side drag signals */
346 static void gtk_text_view_drag_begin       (GtkWidget        *widget,
347                                             GdkDragContext   *context);
348 static void gtk_text_view_drag_end         (GtkWidget        *widget,
349                                             GdkDragContext   *context);
350 static void gtk_text_view_drag_data_get    (GtkWidget        *widget,
351                                             GdkDragContext   *context,
352                                             GtkSelectionData *selection_data,
353                                             guint             info,
354                                             guint             time);
355 static void gtk_text_view_drag_data_delete (GtkWidget        *widget,
356                                             GdkDragContext   *context);
357
358 /* Target side drag signals */
359 static void     gtk_text_view_drag_leave         (GtkWidget        *widget,
360                                                   GdkDragContext   *context,
361                                                   guint             time);
362 static gboolean gtk_text_view_drag_motion        (GtkWidget        *widget,
363                                                   GdkDragContext   *context,
364                                                   gint              x,
365                                                   gint              y,
366                                                   guint             time);
367 static gboolean gtk_text_view_drag_drop          (GtkWidget        *widget,
368                                                   GdkDragContext   *context,
369                                                   gint              x,
370                                                   gint              y,
371                                                   guint             time);
372 static void     gtk_text_view_drag_data_received (GtkWidget        *widget,
373                                                   GdkDragContext   *context,
374                                                   gint              x,
375                                                   gint              y,
376                                                   GtkSelectionData *selection_data,
377                                                   guint             info,
378                                                   guint             time);
379
380 static gboolean gtk_text_view_popup_menu         (GtkWidget     *widget);
381
382 static void gtk_text_view_move_cursor       (GtkTextView           *text_view,
383                                              GtkMovementStep        step,
384                                              gint                   count,
385                                              gboolean               extend_selection);
386 static void gtk_text_view_move_viewport     (GtkTextView           *text_view,
387                                              GtkScrollStep          step,
388                                              gint                   count);
389 static void gtk_text_view_set_anchor       (GtkTextView           *text_view);
390 static gboolean gtk_text_view_scroll_pages (GtkTextView           *text_view,
391                                             gint                   count,
392                                             gboolean               extend_selection);
393 static gboolean gtk_text_view_scroll_hpages(GtkTextView           *text_view,
394                                             gint                   count,
395                                             gboolean               extend_selection);
396 static void gtk_text_view_insert_at_cursor (GtkTextView           *text_view,
397                                             const gchar           *str);
398 static void gtk_text_view_delete_from_cursor (GtkTextView           *text_view,
399                                               GtkDeleteType          type,
400                                               gint                   count);
401 static void gtk_text_view_backspace        (GtkTextView           *text_view);
402 static void gtk_text_view_cut_clipboard    (GtkTextView           *text_view);
403 static void gtk_text_view_copy_clipboard   (GtkTextView           *text_view);
404 static void gtk_text_view_paste_clipboard  (GtkTextView           *text_view);
405 static void gtk_text_view_toggle_overwrite (GtkTextView           *text_view);
406 static void gtk_text_view_toggle_cursor_visible (GtkTextView      *text_view);
407
408 static void gtk_text_view_unselect         (GtkTextView           *text_view);
409
410 static void     gtk_text_view_validate_onscreen     (GtkTextView        *text_view);
411 static void     gtk_text_view_get_first_para_iter   (GtkTextView        *text_view,
412                                                      GtkTextIter        *iter);
413 static void     gtk_text_view_update_layout_width       (GtkTextView        *text_view);
414 static void     gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
415                                                          GtkTextAttributes  *values);
416 static void     gtk_text_view_ensure_layout          (GtkTextView        *text_view);
417 static void     gtk_text_view_destroy_layout         (GtkTextView        *text_view);
418 static void     gtk_text_view_check_keymap_direction (GtkTextView        *text_view);
419 static void     gtk_text_view_start_selection_drag   (GtkTextView        *text_view,
420                                                       const GtkTextIter  *iter,
421                                                       GdkEventButton     *event);
422 static gboolean gtk_text_view_end_selection_drag     (GtkTextView        *text_view);
423 static void     gtk_text_view_start_selection_dnd    (GtkTextView        *text_view,
424                                                       const GtkTextIter  *iter,
425                                                       GdkEventMotion     *event);
426 static void     gtk_text_view_check_cursor_blink     (GtkTextView        *text_view);
427 static void     gtk_text_view_pend_cursor_blink      (GtkTextView        *text_view);
428 static void     gtk_text_view_stop_cursor_blink      (GtkTextView        *text_view);
429 static void     gtk_text_view_reset_blink_time       (GtkTextView        *text_view);
430
431 static void     gtk_text_view_value_changed                (GtkAdjustment *adjustment,
432                                                             GtkTextView   *view);
433 static void     gtk_text_view_commit_handler               (GtkIMContext  *context,
434                                                             const gchar   *str,
435                                                             GtkTextView   *text_view);
436 static void     gtk_text_view_commit_text                  (GtkTextView   *text_view,
437                                                             const gchar   *text);
438 static void     gtk_text_view_preedit_changed_handler      (GtkIMContext  *context,
439                                                             GtkTextView   *text_view);
440 static gboolean gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
441                                                             GtkTextView   *text_view);
442 static gboolean gtk_text_view_delete_surrounding_handler   (GtkIMContext  *context,
443                                                             gint           offset,
444                                                             gint           n_chars,
445                                                             GtkTextView   *text_view);
446
447 static void gtk_text_view_mark_set_handler       (GtkTextBuffer     *buffer,
448                                                   const GtkTextIter *location,
449                                                   GtkTextMark       *mark,
450                                                   gpointer           data);
451 static void gtk_text_view_target_list_notify     (GtkTextBuffer     *buffer,
452                                                   const GParamSpec  *pspec,
453                                                   gpointer           data);
454 static void gtk_text_view_paste_done_handler     (GtkTextBuffer     *buffer,
455                                                   GtkClipboard      *clipboard,
456                                                   gpointer           data);
457 static void gtk_text_view_get_virtual_cursor_pos (GtkTextView       *text_view,
458                                                   GtkTextIter       *cursor,
459                                                   gint              *x,
460                                                   gint              *y);
461 static void gtk_text_view_set_virtual_cursor_pos (GtkTextView       *text_view,
462                                                   gint               x,
463                                                   gint               y);
464
465 static void gtk_text_view_do_popup               (GtkTextView       *text_view,
466                                                   GdkEventButton    *event);
467
468 static void cancel_pending_scroll                (GtkTextView   *text_view);
469 static void gtk_text_view_queue_scroll           (GtkTextView   *text_view,
470                                                   GtkTextMark   *mark,
471                                                   gdouble        within_margin,
472                                                   gboolean       use_align,
473                                                   gdouble        xalign,
474                                                   gdouble        yalign);
475
476 static gboolean gtk_text_view_flush_scroll         (GtkTextView *text_view);
477 static void     gtk_text_view_update_adjustments   (GtkTextView *text_view);
478 static void     gtk_text_view_invalidate           (GtkTextView *text_view);
479 static void     gtk_text_view_flush_first_validate (GtkTextView *text_view);
480
481 static void     gtk_text_view_set_hadjustment        (GtkTextView   *text_view,
482                                                       GtkAdjustment *adjustment);
483 static void     gtk_text_view_set_vadjustment        (GtkTextView   *text_view,
484                                                       GtkAdjustment *adjustment);
485 static void     gtk_text_view_set_hadjustment_values (GtkTextView   *text_view);
486 static void     gtk_text_view_set_vadjustment_values (GtkTextView   *text_view);
487
488 static void gtk_text_view_update_im_spot_location (GtkTextView *text_view);
489
490 /* Container methods */
491 static void gtk_text_view_add    (GtkContainer *container,
492                                   GtkWidget    *child);
493 static void gtk_text_view_remove (GtkContainer *container,
494                                   GtkWidget    *child);
495 static void gtk_text_view_forall (GtkContainer *container,
496                                   gboolean      include_internals,
497                                   GtkCallback   callback,
498                                   gpointer      callback_data);
499
500 /* FIXME probably need the focus methods. */
501
502 typedef struct _GtkTextViewChild GtkTextViewChild;
503
504 struct _GtkTextViewChild
505 {
506   GtkWidget *widget;
507
508   GtkTextChildAnchor *anchor;
509
510   gint from_top_of_line;
511   gint from_left_of_buffer;
512   
513   /* These are ignored if anchor != NULL */
514   GtkTextWindowType type;
515   gint x;
516   gint y;
517 };
518
519 static GtkTextViewChild* text_view_child_new_anchored      (GtkWidget          *child,
520                                                             GtkTextChildAnchor *anchor,
521                                                             GtkTextLayout      *layout);
522 static GtkTextViewChild* text_view_child_new_window        (GtkWidget          *child,
523                                                             GtkTextWindowType   type,
524                                                             gint                x,
525                                                             gint                y);
526 static void              text_view_child_free              (GtkTextViewChild   *child);
527 static void              text_view_child_set_parent_window (GtkTextView        *text_view,
528                                                             GtkTextViewChild   *child);
529
530 struct _GtkTextWindow
531 {
532   GtkTextWindowType type;
533   GtkWidget *widget;
534   GdkWindow *window;
535   GdkWindow *bin_window;
536   GtkRequisition requisition;
537   GdkRectangle allocation;
538 };
539
540 static GtkTextWindow *text_window_new             (GtkTextWindowType  type,
541                                                    GtkWidget         *widget,
542                                                    gint               width_request,
543                                                    gint               height_request);
544 static void           text_window_free            (GtkTextWindow     *win);
545 static void           text_window_realize         (GtkTextWindow     *win,
546                                                    GtkWidget         *widget);
547 static void           text_window_unrealize       (GtkTextWindow     *win);
548 static void           text_window_size_allocate   (GtkTextWindow     *win,
549                                                    GdkRectangle      *rect);
550 static void           text_window_scroll          (GtkTextWindow     *win,
551                                                    gint               dx,
552                                                    gint               dy);
553 static void           text_window_invalidate_rect (GtkTextWindow     *win,
554                                                    GdkRectangle      *rect);
555 static void           text_window_invalidate_cursors (GtkTextWindow  *win);
556
557 static gint           text_window_get_width       (GtkTextWindow     *win);
558 static gint           text_window_get_height      (GtkTextWindow     *win);
559
560
561 static guint signals[LAST_SIGNAL] = { 0 };
562
563 G_DEFINE_TYPE_WITH_CODE (GtkTextView, gtk_text_view, GTK_TYPE_CONTAINER,
564                          G_IMPLEMENT_INTERFACE (GTK_TYPE_SCROLLABLE, NULL))
565
566 static void
567 add_move_binding (GtkBindingSet  *binding_set,
568                   guint           keyval,
569                   guint           modmask,
570                   GtkMovementStep step,
571                   gint            count)
572 {
573   g_assert ((modmask & GDK_SHIFT_MASK) == 0);
574
575   gtk_binding_entry_add_signal (binding_set, keyval, modmask,
576                                 "move-cursor", 3,
577                                 G_TYPE_ENUM, step,
578                                 G_TYPE_INT, count,
579                                 G_TYPE_BOOLEAN, FALSE);
580
581   /* Selection-extending version */
582   gtk_binding_entry_add_signal (binding_set, keyval, modmask | GDK_SHIFT_MASK,
583                                 "move-cursor", 3,
584                                 G_TYPE_ENUM, step,
585                                 G_TYPE_INT, count,
586                                 G_TYPE_BOOLEAN, TRUE);
587 }
588
589 static void
590 gtk_text_view_class_init (GtkTextViewClass *klass)
591 {
592   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
593   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
594   GtkContainerClass *container_class = GTK_CONTAINER_CLASS (klass);
595   GtkBindingSet *binding_set;
596
597   /* Default handlers and virtual methods
598    */
599   gobject_class->set_property = gtk_text_view_set_property;
600   gobject_class->get_property = gtk_text_view_get_property;
601   gobject_class->finalize = gtk_text_view_finalize;
602
603   widget_class->destroy = gtk_text_view_destroy;
604   widget_class->realize = gtk_text_view_realize;
605   widget_class->unrealize = gtk_text_view_unrealize;
606   widget_class->style_updated = gtk_text_view_style_updated;
607   widget_class->direction_changed = gtk_text_view_direction_changed;
608   widget_class->grab_notify = gtk_text_view_grab_notify;
609   widget_class->state_flags_changed = gtk_text_view_state_flags_changed;
610   widget_class->get_preferred_width = gtk_text_view_get_preferred_width;
611   widget_class->get_preferred_height = gtk_text_view_get_preferred_height;
612   widget_class->size_allocate = gtk_text_view_size_allocate;
613   widget_class->event = gtk_text_view_event;
614   widget_class->key_press_event = gtk_text_view_key_press_event;
615   widget_class->key_release_event = gtk_text_view_key_release_event;
616   widget_class->button_press_event = gtk_text_view_button_press_event;
617   widget_class->button_release_event = gtk_text_view_button_release_event;
618   widget_class->focus_in_event = gtk_text_view_focus_in_event;
619   widget_class->focus_out_event = gtk_text_view_focus_out_event;
620   widget_class->motion_notify_event = gtk_text_view_motion_event;
621   widget_class->draw = gtk_text_view_draw;
622   widget_class->focus = gtk_text_view_focus;
623   widget_class->drag_begin = gtk_text_view_drag_begin;
624   widget_class->drag_end = gtk_text_view_drag_end;
625   widget_class->drag_data_get = gtk_text_view_drag_data_get;
626   widget_class->drag_data_delete = gtk_text_view_drag_data_delete;
627
628   widget_class->drag_leave = gtk_text_view_drag_leave;
629   widget_class->drag_motion = gtk_text_view_drag_motion;
630   widget_class->drag_drop = gtk_text_view_drag_drop;
631   widget_class->drag_data_received = gtk_text_view_drag_data_received;
632
633   widget_class->popup_menu = gtk_text_view_popup_menu;
634   
635   container_class->add = gtk_text_view_add;
636   container_class->remove = gtk_text_view_remove;
637   container_class->forall = gtk_text_view_forall;
638
639   klass->move_cursor = gtk_text_view_move_cursor;
640   klass->set_anchor = gtk_text_view_set_anchor;
641   klass->insert_at_cursor = gtk_text_view_insert_at_cursor;
642   klass->delete_from_cursor = gtk_text_view_delete_from_cursor;
643   klass->backspace = gtk_text_view_backspace;
644   klass->cut_clipboard = gtk_text_view_cut_clipboard;
645   klass->copy_clipboard = gtk_text_view_copy_clipboard;
646   klass->paste_clipboard = gtk_text_view_paste_clipboard;
647   klass->toggle_overwrite = gtk_text_view_toggle_overwrite;
648
649   /*
650    * Properties
651    */
652  
653   g_object_class_install_property (gobject_class,
654                                    PROP_PIXELS_ABOVE_LINES,
655                                    g_param_spec_int ("pixels-above-lines",
656                                                      P_("Pixels Above Lines"),
657                                                      P_("Pixels of blank space above paragraphs"),
658                                                      0,
659                                                      G_MAXINT,
660                                                      0,
661                                                      GTK_PARAM_READWRITE));
662  
663   g_object_class_install_property (gobject_class,
664                                    PROP_PIXELS_BELOW_LINES,
665                                    g_param_spec_int ("pixels-below-lines",
666                                                      P_("Pixels Below Lines"),
667                                                      P_("Pixels of blank space below paragraphs"),
668                                                      0,
669                                                      G_MAXINT,
670                                                      0,
671                                                      GTK_PARAM_READWRITE));
672  
673   g_object_class_install_property (gobject_class,
674                                    PROP_PIXELS_INSIDE_WRAP,
675                                    g_param_spec_int ("pixels-inside-wrap",
676                                                      P_("Pixels Inside Wrap"),
677                                                      P_("Pixels of blank space between wrapped lines in a paragraph"),
678                                                      0,
679                                                      G_MAXINT,
680                                                      0,
681                                                      GTK_PARAM_READWRITE));
682
683   g_object_class_install_property (gobject_class,
684                                    PROP_EDITABLE,
685                                    g_param_spec_boolean ("editable",
686                                                          P_("Editable"),
687                                                          P_("Whether the text can be modified by the user"),
688                                                          TRUE,
689                                                          GTK_PARAM_READWRITE));
690
691   g_object_class_install_property (gobject_class,
692                                    PROP_WRAP_MODE,
693                                    g_param_spec_enum ("wrap-mode",
694                                                       P_("Wrap Mode"),
695                                                       P_("Whether to wrap lines never, at word boundaries, or at character boundaries"),
696                                                       GTK_TYPE_WRAP_MODE,
697                                                       GTK_WRAP_NONE,
698                                                       GTK_PARAM_READWRITE));
699  
700   g_object_class_install_property (gobject_class,
701                                    PROP_JUSTIFICATION,
702                                    g_param_spec_enum ("justification",
703                                                       P_("Justification"),
704                                                       P_("Left, right, or center justification"),
705                                                       GTK_TYPE_JUSTIFICATION,
706                                                       GTK_JUSTIFY_LEFT,
707                                                       GTK_PARAM_READWRITE));
708  
709   g_object_class_install_property (gobject_class,
710                                    PROP_LEFT_MARGIN,
711                                    g_param_spec_int ("left-margin",
712                                                      P_("Left Margin"),
713                                                      P_("Width of the left margin in pixels"),
714                                                      0,
715                                                      G_MAXINT,
716                                                      0,
717                                                      GTK_PARAM_READWRITE));
718
719   g_object_class_install_property (gobject_class,
720                                    PROP_RIGHT_MARGIN,
721                                    g_param_spec_int ("right-margin",
722                                                      P_("Right Margin"),
723                                                      P_("Width of the right margin in pixels"),
724                                                      0,
725                                                      G_MAXINT,
726                                                      0,
727                                                      GTK_PARAM_READWRITE));
728
729   g_object_class_install_property (gobject_class,
730                                    PROP_INDENT,
731                                    g_param_spec_int ("indent",
732                                                      P_("Indent"),
733                                                      P_("Amount to indent the paragraph, in pixels"),
734                                                      G_MININT,
735                                                      G_MAXINT,
736                                                      0,
737                                                      GTK_PARAM_READWRITE));
738
739   g_object_class_install_property (gobject_class,
740                                    PROP_TABS,
741                                    g_param_spec_boxed ("tabs",
742                                                        P_("Tabs"),
743                                                        P_("Custom tabs for this text"),
744                                                        PANGO_TYPE_TAB_ARRAY,
745                                                        GTK_PARAM_READWRITE));
746
747   g_object_class_install_property (gobject_class,
748                                    PROP_CURSOR_VISIBLE,
749                                    g_param_spec_boolean ("cursor-visible",
750                                                          P_("Cursor Visible"),
751                                                          P_("If the insertion cursor is shown"),
752                                                          TRUE,
753                                                          GTK_PARAM_READWRITE));
754
755   g_object_class_install_property (gobject_class,
756                                    PROP_BUFFER,
757                                    g_param_spec_object ("buffer",
758                                                         P_("Buffer"),
759                                                         P_("The buffer which is displayed"),
760                                                         GTK_TYPE_TEXT_BUFFER,
761                                                         GTK_PARAM_READWRITE));
762
763   g_object_class_install_property (gobject_class,
764                                    PROP_OVERWRITE,
765                                    g_param_spec_boolean ("overwrite",
766                                                          P_("Overwrite mode"),
767                                                          P_("Whether entered text overwrites existing contents"),
768                                                          FALSE,
769                                                          GTK_PARAM_READWRITE));
770
771   g_object_class_install_property (gobject_class,
772                                    PROP_ACCEPTS_TAB,
773                                    g_param_spec_boolean ("accepts-tab",
774                                                          P_("Accepts tab"),
775                                                          P_("Whether Tab will result in a tab character being entered"),
776                                                          TRUE,
777                                                          GTK_PARAM_READWRITE));
778
779    /**
780     * GtkTextView:im-module:
781     *
782     * Which IM (input method) module should be used for this entry. 
783     * See #GtkIMContext.
784     *
785     * Setting this to a non-%NULL value overrides the
786     * system-wide IM module setting. See the GtkSettings 
787     * #GtkSettings:gtk-im-module property.
788     *
789     * Since: 2.16
790     */
791    g_object_class_install_property (gobject_class,
792                                     PROP_IM_MODULE,
793                                     g_param_spec_string ("im-module",
794                                                          P_("IM module"),
795                                                          P_("Which IM module should be used"),
796                                                          NULL,
797                                                          GTK_PARAM_READWRITE));
798
799    /* GtkScrollable interface */
800    g_object_class_override_property (gobject_class, PROP_HADJUSTMENT,    "hadjustment");
801    g_object_class_override_property (gobject_class, PROP_VADJUSTMENT,    "vadjustment");
802    g_object_class_override_property (gobject_class, PROP_HSCROLL_POLICY, "hscroll-policy");
803    g_object_class_override_property (gobject_class, PROP_VSCROLL_POLICY, "vscroll-policy");
804
805   /*
806    * Style properties
807    */
808   gtk_widget_class_install_style_property (widget_class,
809                                            g_param_spec_boxed ("error-underline-color",
810                                                                P_("Error underline color"),
811                                                                P_("Color with which to draw error-indication underlines"),
812                                                                GDK_TYPE_COLOR,
813                                                                GTK_PARAM_READABLE));
814   
815   /*
816    * Signals
817    */
818
819   /**
820    * GtkTextView::move-cursor: 
821    * @text_view: the object which received the signal
822    * @step: the granularity of the move, as a #GtkMovementStep
823    * @count: the number of @step units to move
824    * @extend_selection: %TRUE if the move should extend the selection
825    *  
826    * The ::move-cursor signal is a 
827    * <link linkend="keybinding-signals">keybinding signal</link> 
828    * which gets emitted when the user initiates a cursor movement. 
829    * If the cursor is not visible in @text_view, this signal causes
830    * the viewport to be moved instead.
831    *
832    * Applications should not connect to it, but may emit it with 
833    * g_signal_emit_by_name() if they need to control the cursor
834    * programmatically.
835    *
836    * The default bindings for this signal come in two variants,
837    * the variant with the Shift modifier extends the selection,
838    * the variant without the Shift modifer does not.
839    * There are too many key combinations to list them all here.
840    * <itemizedlist>
841    * <listitem>Arrow keys move by individual characters/lines</listitem>
842    * <listitem>Ctrl-arrow key combinations move by words/paragraphs</listitem>
843    * <listitem>Home/End keys move to the ends of the buffer</listitem>
844    * <listitem>PageUp/PageDown keys move vertically by pages</listitem>
845    * <listitem>Ctrl-PageUp/PageDown keys move horizontally by pages</listitem>
846    * </itemizedlist>
847    */
848   signals[MOVE_CURSOR] = 
849     g_signal_new (I_("move-cursor"),
850                   G_OBJECT_CLASS_TYPE (gobject_class), 
851                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, 
852                   G_STRUCT_OFFSET (GtkTextViewClass, move_cursor),
853                   NULL, NULL, 
854                   _gtk_marshal_VOID__ENUM_INT_BOOLEAN, 
855                   G_TYPE_NONE, 3,
856                   GTK_TYPE_MOVEMENT_STEP, 
857                   G_TYPE_INT, 
858                   G_TYPE_BOOLEAN);
859
860   /**
861    * GtkTextView::move-viewport:
862    * @text_view: the object which received the signal
863    * @step: the granularity of the move, as a #GtkMovementStep
864    * @count: the number of @step units to move
865    *
866    * The ::move-viewport signal is a 
867    * <link linkend="keybinding-signals">keybinding signal</link> 
868    * which can be bound to key combinations to allow the user
869    * to move the viewport, i.e. change what part of the text view
870    * is visible in a containing scrolled window.
871    *
872    * There are no default bindings for this signal.
873    */
874   signals[MOVE_VIEWPORT] =
875     g_signal_new_class_handler (I_("move-viewport"),
876                                 G_OBJECT_CLASS_TYPE (gobject_class),
877                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
878                                 G_CALLBACK (gtk_text_view_move_viewport),
879                                 NULL, NULL,
880                                 _gtk_marshal_VOID__ENUM_INT,
881                                 G_TYPE_NONE, 2,
882                                 GTK_TYPE_SCROLL_STEP,
883                                 G_TYPE_INT);
884
885   /**
886    * GtkTextView::set-anchor:
887    * @text_view: the object which received the signal
888    *
889    * The ::set-anchor signal is a
890    * <link linkend="keybinding-signals">keybinding signal</link>
891    * which gets emitted when the user initiates setting the "anchor" 
892    * mark. The "anchor" mark gets placed at the same position as the
893    * "insert" mark.
894    *
895    * This signal has no default bindings.
896    */   
897   signals[SET_ANCHOR] =
898     g_signal_new (I_("set-anchor"),
899                   G_OBJECT_CLASS_TYPE (gobject_class),
900                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
901                   G_STRUCT_OFFSET (GtkTextViewClass, set_anchor),
902                   NULL, NULL,
903                   _gtk_marshal_VOID__VOID,
904                   G_TYPE_NONE, 0);
905
906   /**
907    * GtkTextView::insert-at-cursor:
908    * @text_view: the object which received the signal
909    * @string: the string to insert
910    *
911    * The ::insert-at-cursor signal is a
912    * <link linkend="keybinding-signals">keybinding signal</link>
913    * which gets emitted when the user initiates the insertion of a 
914    * fixed string at the cursor.
915    *
916    * This signal has no default bindings.
917    */
918   signals[INSERT_AT_CURSOR] =
919     g_signal_new (I_("insert-at-cursor"),
920                   G_OBJECT_CLASS_TYPE (gobject_class),
921                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
922                   G_STRUCT_OFFSET (GtkTextViewClass, insert_at_cursor),
923                   NULL, NULL,
924                   _gtk_marshal_VOID__STRING,
925                   G_TYPE_NONE, 1,
926                   G_TYPE_STRING);
927
928   /**
929    * GtkTextView::delete-from-cursor:
930    * @text_view: the object which received the signal
931    * @type: the granularity of the deletion, as a #GtkDeleteType
932    * @count: the number of @type units to delete
933    *
934    * The ::delete-from-cursor signal is a 
935    * <link linkend="keybinding-signals">keybinding signal</link> 
936    * which gets emitted when the user initiates a text deletion.
937    *
938    * If the @type is %GTK_DELETE_CHARS, GTK+ deletes the selection
939    * if there is one, otherwise it deletes the requested number
940    * of characters.
941    *
942    * The default bindings for this signal are
943    * Delete for deleting a character, Ctrl-Delete for 
944    * deleting a word and Ctrl-Backspace for deleting a word 
945    * backwords.
946    */
947   signals[DELETE_FROM_CURSOR] =
948     g_signal_new (I_("delete-from-cursor"),
949                   G_OBJECT_CLASS_TYPE (gobject_class),
950                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
951                   G_STRUCT_OFFSET (GtkTextViewClass, delete_from_cursor),
952                   NULL, NULL,
953                   _gtk_marshal_VOID__ENUM_INT,
954                   G_TYPE_NONE, 2,
955                   GTK_TYPE_DELETE_TYPE,
956                   G_TYPE_INT);
957
958   /**
959    * GtkTextView::backspace:
960    * @text_view: the object which received the signal
961    *
962    * The ::backspace signal is a 
963    * <link linkend="keybinding-signals">keybinding signal</link> 
964    * which gets emitted when the user asks for it.
965    * 
966    * The default bindings for this signal are
967    * Backspace and Shift-Backspace.
968    */
969   signals[BACKSPACE] =
970     g_signal_new (I_("backspace"),
971                   G_OBJECT_CLASS_TYPE (gobject_class),
972                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
973                   G_STRUCT_OFFSET (GtkTextViewClass, backspace),
974                   NULL, NULL,
975                   _gtk_marshal_VOID__VOID,
976                   G_TYPE_NONE, 0);
977
978   /**
979    * GtkTextView::cut-clipboard:
980    * @text_view: the object which received the signal
981    *
982    * The ::cut-clipboard signal is a 
983    * <link linkend="keybinding-signals">keybinding signal</link> 
984    * which gets emitted to cut the selection to the clipboard.
985    * 
986    * The default bindings for this signal are
987    * Ctrl-x and Shift-Delete.
988    */
989   signals[CUT_CLIPBOARD] =
990     g_signal_new (I_("cut-clipboard"),
991                   G_OBJECT_CLASS_TYPE (gobject_class),
992                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
993                   G_STRUCT_OFFSET (GtkTextViewClass, cut_clipboard),
994                   NULL, NULL,
995                   _gtk_marshal_VOID__VOID,
996                   G_TYPE_NONE, 0);
997
998   /**
999    * GtkTextView::copy-clipboard:
1000    * @text_view: the object which received the signal
1001    *
1002    * The ::copy-clipboard signal is a 
1003    * <link linkend="keybinding-signals">keybinding signal</link> 
1004    * which gets emitted to copy the selection to the clipboard.
1005    * 
1006    * The default bindings for this signal are
1007    * Ctrl-c and Ctrl-Insert.
1008    */
1009   signals[COPY_CLIPBOARD] =
1010     g_signal_new (I_("copy-clipboard"),
1011                   G_OBJECT_CLASS_TYPE (gobject_class),
1012                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1013                   G_STRUCT_OFFSET (GtkTextViewClass, copy_clipboard),
1014                   NULL, NULL,
1015                   _gtk_marshal_VOID__VOID,
1016                   G_TYPE_NONE, 0);
1017
1018   /**
1019    * GtkTextView::paste-clipboard:
1020    * @text_view: the object which received the signal
1021    *
1022    * The ::paste-clipboard signal is a 
1023    * <link linkend="keybinding-signals">keybinding signal</link> 
1024    * which gets emitted to paste the contents of the clipboard 
1025    * into the text view.
1026    * 
1027    * The default bindings for this signal are
1028    * Ctrl-v and Shift-Insert.
1029    */
1030   signals[PASTE_CLIPBOARD] =
1031     g_signal_new (I_("paste-clipboard"),
1032                   G_OBJECT_CLASS_TYPE (gobject_class),
1033                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1034                   G_STRUCT_OFFSET (GtkTextViewClass, paste_clipboard),
1035                   NULL, NULL,
1036                   _gtk_marshal_VOID__VOID,
1037                   G_TYPE_NONE, 0);
1038
1039   /**
1040    * GtkTextView::toggle-overwrite:
1041    * @text_view: the object which received the signal
1042    *
1043    * The ::toggle-overwrite signal is a 
1044    * <link linkend="keybinding-signals">keybinding signal</link> 
1045    * which gets emitted to toggle the overwrite mode of the text view.
1046    * 
1047    * The default bindings for this signal is Insert.
1048    */ 
1049   signals[TOGGLE_OVERWRITE] =
1050     g_signal_new (I_("toggle-overwrite"),
1051                   G_OBJECT_CLASS_TYPE (gobject_class),
1052                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1053                   G_STRUCT_OFFSET (GtkTextViewClass, toggle_overwrite),
1054                   NULL, NULL,
1055                   _gtk_marshal_VOID__VOID,
1056                   G_TYPE_NONE, 0);
1057
1058   /**
1059    * GtkTextView::populate-popup:
1060    * @entry: The text view on which the signal is emitted
1061    * @menu: the menu that is being populated
1062    *
1063    * The ::populate-popup signal gets emitted before showing the 
1064    * context menu of the text view.
1065    *
1066    * If you need to add items to the context menu, connect
1067    * to this signal and append your menuitems to the @menu.
1068    */
1069   signals[POPULATE_POPUP] =
1070     g_signal_new (I_("populate-popup"),
1071                   G_OBJECT_CLASS_TYPE (gobject_class),
1072                   G_SIGNAL_RUN_LAST,
1073                   G_STRUCT_OFFSET (GtkTextViewClass, populate_popup),
1074                   NULL, NULL,
1075                   _gtk_marshal_VOID__OBJECT,
1076                   G_TYPE_NONE, 1,
1077                   GTK_TYPE_MENU);
1078   
1079   /**
1080    * GtkTextView::select-all:
1081    * @text_view: the object which received the signal
1082    * @select: %TRUE to select, %FALSE to unselect
1083    *
1084    * The ::select-all signal is a 
1085    * <link linkend="keybinding-signals">keybinding signal</link> 
1086    * which gets emitted to select or unselect the complete
1087    * contents of the text view.
1088    *
1089    * The default bindings for this signal are Ctrl-a and Ctrl-/ 
1090    * for selecting and Shift-Ctrl-a and Ctrl-\ for unselecting.
1091    */
1092   signals[SELECT_ALL] =
1093     g_signal_new_class_handler (I_("select-all"),
1094                                 G_OBJECT_CLASS_TYPE (gobject_class),
1095                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1096                                 G_CALLBACK (gtk_text_view_select_all),
1097                                 NULL, NULL,
1098                                 _gtk_marshal_VOID__BOOLEAN,
1099                                 G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
1100
1101   /**
1102    * GtkTextView::toggle-cursor-visible:
1103    * @text_view: the object which received the signal
1104    *
1105    * The ::toggle-cursor-visible signal is a 
1106    * <link linkend="keybinding-signals">keybinding signal</link> 
1107    * which gets emitted to toggle the visibility of the cursor.
1108    *
1109    * The default binding for this signal is F7.
1110    */ 
1111   signals[TOGGLE_CURSOR_VISIBLE] =
1112     g_signal_new_class_handler (I_("toggle-cursor-visible"),
1113                                 G_OBJECT_CLASS_TYPE (gobject_class),
1114                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1115                                 G_CALLBACK (gtk_text_view_toggle_cursor_visible),
1116                                 NULL, NULL,
1117                                 _gtk_marshal_VOID__VOID,
1118                                 G_TYPE_NONE, 0);
1119
1120   /**
1121    * GtkTextView::preedit-changed:
1122    * @text_view: the object which received the signal
1123    * @preedit: the current preedit string
1124    *
1125    * If an input method is used, the typed text will not immediately
1126    * be committed to the buffer. So if you are interested in the text,
1127    * connect to this signal.
1128    *
1129    * This signal is only emitted if the text at the given position
1130    * is actually editable.
1131    *
1132    * Since: 2.20
1133    */
1134   signals[PREEDIT_CHANGED] =
1135     g_signal_new_class_handler (I_("preedit-changed"),
1136                                 G_OBJECT_CLASS_TYPE (gobject_class),
1137                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1138                                 NULL,
1139                                 NULL, NULL,
1140                                 _gtk_marshal_VOID__STRING,
1141                                 G_TYPE_NONE, 1,
1142                                 G_TYPE_STRING);
1143
1144   /*
1145    * Key bindings
1146    */
1147
1148   binding_set = gtk_binding_set_by_class (klass);
1149   
1150   /* Moving the insertion point */
1151   add_move_binding (binding_set, GDK_KEY_Right, 0,
1152                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
1153
1154   add_move_binding (binding_set, GDK_KEY_KP_Right, 0,
1155                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
1156   
1157   add_move_binding (binding_set, GDK_KEY_Left, 0,
1158                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
1159
1160   add_move_binding (binding_set, GDK_KEY_KP_Left, 0,
1161                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
1162   
1163   add_move_binding (binding_set, GDK_KEY_Right, GDK_CONTROL_MASK,
1164                     GTK_MOVEMENT_WORDS, 1);
1165
1166   add_move_binding (binding_set, GDK_KEY_KP_Right, GDK_CONTROL_MASK,
1167                     GTK_MOVEMENT_WORDS, 1);
1168   
1169   add_move_binding (binding_set, GDK_KEY_Left, GDK_CONTROL_MASK,
1170                     GTK_MOVEMENT_WORDS, -1);
1171
1172   add_move_binding (binding_set, GDK_KEY_KP_Left, GDK_CONTROL_MASK,
1173                     GTK_MOVEMENT_WORDS, -1);
1174   
1175   add_move_binding (binding_set, GDK_KEY_Up, 0,
1176                     GTK_MOVEMENT_DISPLAY_LINES, -1);
1177
1178   add_move_binding (binding_set, GDK_KEY_KP_Up, 0,
1179                     GTK_MOVEMENT_DISPLAY_LINES, -1);
1180   
1181   add_move_binding (binding_set, GDK_KEY_Down, 0,
1182                     GTK_MOVEMENT_DISPLAY_LINES, 1);
1183
1184   add_move_binding (binding_set, GDK_KEY_KP_Down, 0,
1185                     GTK_MOVEMENT_DISPLAY_LINES, 1);
1186   
1187   add_move_binding (binding_set, GDK_KEY_Up, GDK_CONTROL_MASK,
1188                     GTK_MOVEMENT_PARAGRAPHS, -1);
1189
1190   add_move_binding (binding_set, GDK_KEY_KP_Up, GDK_CONTROL_MASK,
1191                     GTK_MOVEMENT_PARAGRAPHS, -1);
1192   
1193   add_move_binding (binding_set, GDK_KEY_Down, GDK_CONTROL_MASK,
1194                     GTK_MOVEMENT_PARAGRAPHS, 1);
1195
1196   add_move_binding (binding_set, GDK_KEY_KP_Down, GDK_CONTROL_MASK,
1197                     GTK_MOVEMENT_PARAGRAPHS, 1);
1198   
1199   add_move_binding (binding_set, GDK_KEY_Home, 0,
1200                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
1201
1202   add_move_binding (binding_set, GDK_KEY_KP_Home, 0,
1203                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
1204   
1205   add_move_binding (binding_set, GDK_KEY_End, 0,
1206                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
1207
1208   add_move_binding (binding_set, GDK_KEY_KP_End, 0,
1209                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
1210   
1211   add_move_binding (binding_set, GDK_KEY_Home, GDK_CONTROL_MASK,
1212                     GTK_MOVEMENT_BUFFER_ENDS, -1);
1213
1214   add_move_binding (binding_set, GDK_KEY_KP_Home, GDK_CONTROL_MASK,
1215                     GTK_MOVEMENT_BUFFER_ENDS, -1);
1216   
1217   add_move_binding (binding_set, GDK_KEY_End, GDK_CONTROL_MASK,
1218                     GTK_MOVEMENT_BUFFER_ENDS, 1);
1219
1220   add_move_binding (binding_set, GDK_KEY_KP_End, GDK_CONTROL_MASK,
1221                     GTK_MOVEMENT_BUFFER_ENDS, 1);
1222   
1223   add_move_binding (binding_set, GDK_KEY_Page_Up, 0,
1224                     GTK_MOVEMENT_PAGES, -1);
1225
1226   add_move_binding (binding_set, GDK_KEY_KP_Page_Up, 0,
1227                     GTK_MOVEMENT_PAGES, -1);
1228   
1229   add_move_binding (binding_set, GDK_KEY_Page_Down, 0,
1230                     GTK_MOVEMENT_PAGES, 1);
1231
1232   add_move_binding (binding_set, GDK_KEY_KP_Page_Down, 0,
1233                     GTK_MOVEMENT_PAGES, 1);
1234
1235   add_move_binding (binding_set, GDK_KEY_Page_Up, GDK_CONTROL_MASK,
1236                     GTK_MOVEMENT_HORIZONTAL_PAGES, -1);
1237
1238   add_move_binding (binding_set, GDK_KEY_KP_Page_Up, GDK_CONTROL_MASK,
1239                     GTK_MOVEMENT_HORIZONTAL_PAGES, -1);
1240   
1241   add_move_binding (binding_set, GDK_KEY_Page_Down, GDK_CONTROL_MASK,
1242                     GTK_MOVEMENT_HORIZONTAL_PAGES, 1);
1243
1244   add_move_binding (binding_set, GDK_KEY_KP_Page_Down, GDK_CONTROL_MASK,
1245                     GTK_MOVEMENT_HORIZONTAL_PAGES, 1);
1246
1247   /* Select all */
1248   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_CONTROL_MASK,
1249                                 "select-all", 1,
1250                                 G_TYPE_BOOLEAN, TRUE);
1251
1252   gtk_binding_entry_add_signal (binding_set, GDK_KEY_slash, GDK_CONTROL_MASK,
1253                                 "select-all", 1,
1254                                 G_TYPE_BOOLEAN, TRUE);
1255   
1256   /* Unselect all */
1257   gtk_binding_entry_add_signal (binding_set, GDK_KEY_backslash, GDK_CONTROL_MASK,
1258                                  "select-all", 1,
1259                                  G_TYPE_BOOLEAN, FALSE);
1260
1261   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1262                                  "select-all", 1,
1263                                  G_TYPE_BOOLEAN, FALSE);
1264
1265   /* Deleting text */
1266   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, 0,
1267                                 "delete-from-cursor", 2,
1268                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
1269                                 G_TYPE_INT, 1);
1270
1271   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, 0,
1272                                 "delete-from-cursor", 2,
1273                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
1274                                 G_TYPE_INT, 1);
1275   
1276   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, 0,
1277                                 "backspace", 0);
1278
1279   /* Make this do the same as Backspace, to help with mis-typing */
1280   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_SHIFT_MASK,
1281                                 "backspace", 0);
1282
1283   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_CONTROL_MASK,
1284                                 "delete-from-cursor", 2,
1285                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1286                                 G_TYPE_INT, 1);
1287
1288   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, GDK_CONTROL_MASK,
1289                                 "delete-from-cursor", 2,
1290                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1291                                 G_TYPE_INT, 1);
1292   
1293   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_CONTROL_MASK,
1294                                 "delete-from-cursor", 2,
1295                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1296                                 G_TYPE_INT, -1);
1297
1298   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1299                                 "delete-from-cursor", 2,
1300                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1301                                 G_TYPE_INT, 1);
1302
1303   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1304                                 "delete-from-cursor", 2,
1305                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1306                                 G_TYPE_INT, 1);
1307
1308   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1309                                 "delete-from-cursor", 2,
1310                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1311                                 G_TYPE_INT, -1);
1312
1313   /* Cut/copy/paste */
1314
1315   gtk_binding_entry_add_signal (binding_set, GDK_KEY_x, GDK_CONTROL_MASK,
1316                                 "cut-clipboard", 0);
1317   gtk_binding_entry_add_signal (binding_set, GDK_KEY_c, GDK_CONTROL_MASK,
1318                                 "copy-clipboard", 0);
1319   gtk_binding_entry_add_signal (binding_set, GDK_KEY_v, GDK_CONTROL_MASK,
1320                                 "paste-clipboard", 0);
1321
1322   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_SHIFT_MASK,
1323                                 "cut-clipboard", 0);
1324   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, GDK_CONTROL_MASK,
1325                                 "copy-clipboard", 0);
1326   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, GDK_SHIFT_MASK,
1327                                 "paste-clipboard", 0);
1328
1329   /* Overwrite */
1330   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, 0,
1331                                 "toggle-overwrite", 0);
1332   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Insert, 0,
1333                                 "toggle-overwrite", 0);
1334
1335   /* Caret mode */
1336   gtk_binding_entry_add_signal (binding_set, GDK_KEY_F7, 0,
1337                                 "toggle-cursor-visible", 0);
1338
1339   /* Control-tab focus motion */
1340   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Tab, GDK_CONTROL_MASK,
1341                                 "move-focus", 1,
1342                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_FORWARD);
1343   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Tab, GDK_CONTROL_MASK,
1344                                 "move-focus", 1,
1345                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_FORWARD);
1346   
1347   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Tab, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1348                                 "move-focus", 1,
1349                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_BACKWARD);
1350   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Tab, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1351                                 "move-focus", 1,
1352                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_BACKWARD);
1353
1354   g_type_class_add_private (gobject_class, sizeof (GtkTextViewPrivate));
1355
1356   gtk_widget_class_set_accessible_type (widget_class, GTK_TYPE_TEXT_VIEW_ACCESSIBLE);
1357 }
1358
1359 static void
1360 gtk_text_view_init (GtkTextView *text_view)
1361 {
1362   GtkWidget *widget = GTK_WIDGET (text_view);
1363   GtkTargetList *target_list;
1364   GtkTextViewPrivate *priv;
1365
1366   text_view->priv = GTK_TEXT_VIEW_GET_PRIVATE (text_view);
1367   priv = text_view->priv;
1368
1369   gtk_widget_set_can_focus (widget, TRUE);
1370
1371   /* Set up default style */
1372   priv->wrap_mode = GTK_WRAP_NONE;
1373   priv->pixels_above_lines = 0;
1374   priv->pixels_below_lines = 0;
1375   priv->pixels_inside_wrap = 0;
1376   priv->justify = GTK_JUSTIFY_LEFT;
1377   priv->left_margin = 0;
1378   priv->right_margin = 0;
1379   priv->indent = 0;
1380   priv->tabs = NULL;
1381   priv->editable = TRUE;
1382
1383   priv->scroll_after_paste = TRUE;
1384
1385   gtk_drag_dest_set (widget, 0, NULL, 0,
1386                      GDK_ACTION_COPY | GDK_ACTION_MOVE);
1387
1388   target_list = gtk_target_list_new (NULL, 0);
1389   gtk_drag_dest_set_target_list (widget, target_list);
1390   gtk_target_list_unref (target_list);
1391
1392   priv->virtual_cursor_x = -1;
1393   priv->virtual_cursor_y = -1;
1394
1395   /* This object is completely private. No external entity can gain a reference
1396    * to it; so we create it here and destroy it in finalize ().
1397    */
1398   priv->im_context = gtk_im_multicontext_new ();
1399
1400   g_signal_connect (priv->im_context, "commit",
1401                     G_CALLBACK (gtk_text_view_commit_handler), text_view);
1402   g_signal_connect (priv->im_context, "preedit-changed",
1403                     G_CALLBACK (gtk_text_view_preedit_changed_handler), text_view);
1404   g_signal_connect (priv->im_context, "retrieve-surrounding",
1405                     G_CALLBACK (gtk_text_view_retrieve_surrounding_handler), text_view);
1406   g_signal_connect (priv->im_context, "delete-surrounding",
1407                     G_CALLBACK (gtk_text_view_delete_surrounding_handler), text_view);
1408
1409   priv->cursor_visible = TRUE;
1410
1411   priv->accepts_tab = TRUE;
1412
1413   priv->text_window = text_window_new (GTK_TEXT_WINDOW_TEXT,
1414                                        widget, 200, 200);
1415
1416   priv->drag_start_x = -1;
1417   priv->drag_start_y = -1;
1418
1419   priv->pending_place_cursor_button = 0;
1420
1421   /* We handle all our own redrawing */
1422   gtk_widget_set_redraw_on_allocate (widget, FALSE);
1423 }
1424
1425 /**
1426  * gtk_text_view_new:
1427  *
1428  * Creates a new #GtkTextView. If you don't call gtk_text_view_set_buffer()
1429  * before using the text view, an empty default buffer will be created
1430  * for you. Get the buffer with gtk_text_view_get_buffer(). If you want
1431  * to specify your own buffer, consider gtk_text_view_new_with_buffer().
1432  *
1433  * Return value: a new #GtkTextView
1434  **/
1435 GtkWidget*
1436 gtk_text_view_new (void)
1437 {
1438   return g_object_new (GTK_TYPE_TEXT_VIEW, NULL);
1439 }
1440
1441 /**
1442  * gtk_text_view_new_with_buffer:
1443  * @buffer: a #GtkTextBuffer
1444  *
1445  * Creates a new #GtkTextView widget displaying the buffer
1446  * @buffer. One buffer can be shared among many widgets.
1447  * @buffer may be %NULL to create a default buffer, in which case
1448  * this function is equivalent to gtk_text_view_new(). The
1449  * text view adds its own reference count to the buffer; it does not
1450  * take over an existing reference.
1451  *
1452  * Return value: a new #GtkTextView.
1453  **/
1454 GtkWidget*
1455 gtk_text_view_new_with_buffer (GtkTextBuffer *buffer)
1456 {
1457   GtkTextView *text_view;
1458
1459   text_view = (GtkTextView*)gtk_text_view_new ();
1460
1461   gtk_text_view_set_buffer (text_view, buffer);
1462
1463   return GTK_WIDGET (text_view);
1464 }
1465
1466 /**
1467  * gtk_text_view_set_buffer:
1468  * @text_view: a #GtkTextView
1469  * @buffer: (allow-none): a #GtkTextBuffer
1470  *
1471  * Sets @buffer as the buffer being displayed by @text_view. The previous
1472  * buffer displayed by the text view is unreferenced, and a reference is
1473  * added to @buffer. If you owned a reference to @buffer before passing it
1474  * to this function, you must remove that reference yourself; #GtkTextView
1475  * will not "adopt" it.
1476  **/
1477 void
1478 gtk_text_view_set_buffer (GtkTextView   *text_view,
1479                           GtkTextBuffer *buffer)
1480 {
1481   GtkTextViewPrivate *priv;
1482
1483   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1484   g_return_if_fail (buffer == NULL || GTK_IS_TEXT_BUFFER (buffer));
1485
1486   priv = text_view->priv;
1487
1488   if (priv->buffer == buffer)
1489     return;
1490
1491   if (priv->buffer != NULL)
1492     {
1493       /* Destroy all anchored children */
1494       GSList *tmp_list;
1495       GSList *copy;
1496
1497       copy = g_slist_copy (priv->children);
1498       tmp_list = copy;
1499       while (tmp_list != NULL)
1500         {
1501           GtkTextViewChild *vc = tmp_list->data;
1502
1503           if (vc->anchor)
1504             {
1505               gtk_widget_destroy (vc->widget);
1506               /* vc may now be invalid! */
1507             }
1508
1509           tmp_list = g_slist_next (tmp_list);
1510         }
1511
1512       g_slist_free (copy);
1513
1514       g_signal_handlers_disconnect_by_func (priv->buffer,
1515                                             gtk_text_view_mark_set_handler,
1516                                             text_view);
1517       g_signal_handlers_disconnect_by_func (priv->buffer,
1518                                             gtk_text_view_target_list_notify,
1519                                             text_view);
1520       g_signal_handlers_disconnect_by_func (priv->buffer,
1521                                             gtk_text_view_paste_done_handler,
1522                                             text_view);
1523
1524       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
1525         {
1526           GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
1527                                                               GDK_SELECTION_PRIMARY);
1528           gtk_text_buffer_remove_selection_clipboard (priv->buffer, clipboard);
1529         }
1530
1531       if (priv->layout)
1532         gtk_text_layout_set_buffer (priv->layout, NULL);
1533
1534       g_object_unref (priv->buffer);
1535       priv->dnd_mark = NULL;
1536       priv->first_para_mark = NULL;
1537       cancel_pending_scroll (text_view);
1538     }
1539
1540   priv->buffer = buffer;
1541
1542   if (priv->layout)
1543     gtk_text_layout_set_buffer (priv->layout, buffer);
1544
1545   if (buffer != NULL)
1546     {
1547       GtkTextIter start;
1548
1549       g_object_ref (buffer);
1550
1551       gtk_text_buffer_get_iter_at_offset (priv->buffer, &start, 0);
1552
1553       priv->dnd_mark = gtk_text_buffer_create_mark (priv->buffer,
1554                                                     "gtk_drag_target",
1555                                                     &start, FALSE);
1556
1557       priv->first_para_mark = gtk_text_buffer_create_mark (priv->buffer,
1558                                                            NULL,
1559                                                            &start, TRUE);
1560
1561       priv->first_para_pixels = 0;
1562
1563
1564       g_signal_connect (priv->buffer, "mark-set",
1565                         G_CALLBACK (gtk_text_view_mark_set_handler),
1566                         text_view);
1567       g_signal_connect (priv->buffer, "notify::paste-target-list",
1568                         G_CALLBACK (gtk_text_view_target_list_notify),
1569                         text_view);
1570       g_signal_connect (priv->buffer, "paste-done",
1571                         G_CALLBACK (gtk_text_view_paste_done_handler),
1572                         text_view);
1573
1574       gtk_text_view_target_list_notify (priv->buffer, NULL, text_view);
1575
1576       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
1577         {
1578           GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
1579                                                               GDK_SELECTION_PRIMARY);
1580           gtk_text_buffer_add_selection_clipboard (priv->buffer, clipboard);
1581         }
1582     }
1583
1584   g_object_notify (G_OBJECT (text_view), "buffer");
1585   
1586   if (gtk_widget_get_visible (GTK_WIDGET (text_view)))
1587     gtk_widget_queue_draw (GTK_WIDGET (text_view));
1588
1589   DV(g_print ("Invalidating due to set_buffer\n"));
1590   gtk_text_view_invalidate (text_view);
1591 }
1592
1593 static GtkTextBuffer*
1594 get_buffer (GtkTextView *text_view)
1595 {
1596   if (text_view->priv->buffer == NULL)
1597     {
1598       GtkTextBuffer *b;
1599       b = gtk_text_buffer_new (NULL);
1600       gtk_text_view_set_buffer (text_view, b);
1601       g_object_unref (b);
1602     }
1603
1604   return text_view->priv->buffer;
1605 }
1606
1607 /**
1608  * gtk_text_view_get_buffer:
1609  * @text_view: a #GtkTextView
1610  *
1611  * Returns the #GtkTextBuffer being displayed by this text view.
1612  * The reference count on the buffer is not incremented; the caller
1613  * of this function won't own a new reference.
1614  *
1615  * Return value: (transfer none): a #GtkTextBuffer
1616  **/
1617 GtkTextBuffer*
1618 gtk_text_view_get_buffer (GtkTextView *text_view)
1619 {
1620   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
1621
1622   return get_buffer (text_view);
1623 }
1624
1625 /**
1626  * gtk_text_view_get_cursor_locations:
1627  * @text_view: a #GtkTextView
1628  * @iter: (allow-none): a #GtkTextIter
1629  * @strong: (out) (allow-none): location to store the strong
1630  *     cursor position (may be %NULL)
1631  * @weak: (out) (allow-none): location to store the weak
1632  *     cursor position (may be %NULL)
1633  *
1634  * Given an @iter within a text layout, determine the positions of the
1635  * strong and weak cursors if the insertion point is at that
1636  * iterator. The position of each cursor is stored as a zero-width
1637  * rectangle. The strong cursor location is the location where
1638  * characters of the directionality equal to the base direction of the
1639  * paragraph are inserted.  The weak cursor location is the location
1640  * where characters of the directionality opposite to the base
1641  * direction of the paragraph are inserted.
1642  *
1643  * If @iter is %NULL, the actual cursor position is used.
1644  *
1645  * Note that if @iter happens to be the actual cursor position, and
1646  * there is currently an IM preedit sequence being entered, the
1647  * returned locations will be adjusted to account for the preedit
1648  * cursor's offset within the preedit sequence.
1649  *
1650  * The rectangle position is in buffer coordinates; use
1651  * gtk_text_view_buffer_to_window_coords() to convert these
1652  * coordinates to coordinates for one of the windows in the text view.
1653  *
1654  * Since: 3.0
1655  **/
1656 void
1657 gtk_text_view_get_cursor_locations (GtkTextView       *text_view,
1658                                     const GtkTextIter *iter,
1659                                     GdkRectangle      *strong,
1660                                     GdkRectangle      *weak)
1661 {
1662   GtkTextIter insert;
1663
1664   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1665   g_return_if_fail (iter == NULL ||
1666                     gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1667
1668   gtk_text_view_ensure_layout (text_view);
1669
1670   if (iter)
1671     insert = *iter;
1672   else
1673     gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
1674                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
1675
1676   gtk_text_layout_get_cursor_locations (text_view->priv->layout, &insert,
1677                                         strong, weak);
1678 }
1679
1680 /**
1681  * gtk_text_view_get_iter_at_location:
1682  * @text_view: a #GtkTextView
1683  * @iter: (out): a #GtkTextIter
1684  * @x: x position, in buffer coordinates
1685  * @y: y position, in buffer coordinates
1686  *
1687  * Retrieves the iterator at buffer coordinates @x and @y. Buffer
1688  * coordinates are coordinates for the entire buffer, not just the
1689  * currently-displayed portion.  If you have coordinates from an
1690  * event, you have to convert those to buffer coordinates with
1691  * gtk_text_view_window_to_buffer_coords().
1692  **/
1693 void
1694 gtk_text_view_get_iter_at_location (GtkTextView *text_view,
1695                                     GtkTextIter *iter,
1696                                     gint         x,
1697                                     gint         y)
1698 {
1699   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1700   g_return_if_fail (iter != NULL);
1701
1702   gtk_text_view_ensure_layout (text_view);
1703   
1704   gtk_text_layout_get_iter_at_pixel (text_view->priv->layout,
1705                                      iter, x, y);
1706 }
1707
1708 /**
1709  * gtk_text_view_get_iter_at_position:
1710  * @text_view: a #GtkTextView
1711  * @iter: (out): a #GtkTextIter
1712  * @trailing: (out) (allow-none): if non-%NULL, location to store an integer indicating where
1713  *    in the grapheme the user clicked. It will either be
1714  *    zero, or the number of characters in the grapheme. 
1715  *    0 represents the trailing edge of the grapheme.
1716  * @x: x position, in buffer coordinates
1717  * @y: y position, in buffer coordinates
1718  *
1719  * Retrieves the iterator pointing to the character at buffer 
1720  * coordinates @x and @y. Buffer coordinates are coordinates for 
1721  * the entire buffer, not just the currently-displayed portion.  
1722  * If you have coordinates from an event, you have to convert 
1723  * those to buffer coordinates with 
1724  * gtk_text_view_window_to_buffer_coords().
1725  *
1726  * Note that this is different from gtk_text_view_get_iter_at_location(),
1727  * which returns cursor locations, i.e. positions <emphasis>between</emphasis>
1728  * characters.
1729  *
1730  * Since: 2.6
1731  **/
1732 void
1733 gtk_text_view_get_iter_at_position (GtkTextView *text_view,
1734                                     GtkTextIter *iter,
1735                                     gint        *trailing,
1736                                     gint         x,
1737                                     gint         y)
1738 {
1739   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1740   g_return_if_fail (iter != NULL);
1741
1742   gtk_text_view_ensure_layout (text_view);
1743   
1744   gtk_text_layout_get_iter_at_position (text_view->priv->layout,
1745                                         iter, trailing, x, y);
1746 }
1747
1748 /**
1749  * gtk_text_view_get_iter_location:
1750  * @text_view: a #GtkTextView
1751  * @iter: a #GtkTextIter
1752  * @location: (out): bounds of the character at @iter
1753  *
1754  * Gets a rectangle which roughly contains the character at @iter.
1755  * The rectangle position is in buffer coordinates; use
1756  * gtk_text_view_buffer_to_window_coords() to convert these
1757  * coordinates to coordinates for one of the windows in the text view.
1758  **/
1759 void
1760 gtk_text_view_get_iter_location (GtkTextView       *text_view,
1761                                  const GtkTextIter *iter,
1762                                  GdkRectangle      *location)
1763 {
1764   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1765   g_return_if_fail (gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1766
1767   gtk_text_view_ensure_layout (text_view);
1768   
1769   gtk_text_layout_get_iter_location (text_view->priv->layout, iter, location);
1770 }
1771
1772 /**
1773  * gtk_text_view_get_line_yrange:
1774  * @text_view: a #GtkTextView
1775  * @iter: a #GtkTextIter
1776  * @y: (out): return location for a y coordinate
1777  * @height: (out): return location for a height
1778  *
1779  * Gets the y coordinate of the top of the line containing @iter,
1780  * and the height of the line. The coordinate is a buffer coordinate;
1781  * convert to window coordinates with gtk_text_view_buffer_to_window_coords().
1782  **/
1783 void
1784 gtk_text_view_get_line_yrange (GtkTextView       *text_view,
1785                                const GtkTextIter *iter,
1786                                gint              *y,
1787                                gint              *height)
1788 {
1789   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1790   g_return_if_fail (gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1791
1792   gtk_text_view_ensure_layout (text_view);
1793   
1794   gtk_text_layout_get_line_yrange (text_view->priv->layout,
1795                                    iter,
1796                                    y,
1797                                    height);
1798 }
1799
1800 /**
1801  * gtk_text_view_get_line_at_y:
1802  * @text_view: a #GtkTextView
1803  * @target_iter: (out): a #GtkTextIter
1804  * @y: a y coordinate
1805  * @line_top: (out): return location for top coordinate of the line
1806  *
1807  * Gets the #GtkTextIter at the start of the line containing
1808  * the coordinate @y. @y is in buffer coordinates, convert from
1809  * window coordinates with gtk_text_view_window_to_buffer_coords().
1810  * If non-%NULL, @line_top will be filled with the coordinate of the top
1811  * edge of the line.
1812  **/
1813 void
1814 gtk_text_view_get_line_at_y (GtkTextView *text_view,
1815                              GtkTextIter *target_iter,
1816                              gint         y,
1817                              gint        *line_top)
1818 {
1819   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1820
1821   gtk_text_view_ensure_layout (text_view);
1822   
1823   gtk_text_layout_get_line_at_y (text_view->priv->layout,
1824                                  target_iter,
1825                                  y,
1826                                  line_top);
1827 }
1828
1829 /**
1830  * gtk_text_view_scroll_to_iter:
1831  * @text_view: a #GtkTextView
1832  * @iter: a #GtkTextIter
1833  * @within_margin: margin as a [0.0,0.5) fraction of screen size
1834  * @use_align: whether to use alignment arguments (if %FALSE, 
1835  *    just get the mark onscreen)
1836  * @xalign: horizontal alignment of mark within visible area
1837  * @yalign: vertical alignment of mark within visible area
1838  *
1839  * Scrolls @text_view so that @iter is on the screen in the position
1840  * indicated by @xalign and @yalign. An alignment of 0.0 indicates
1841  * left or top, 1.0 indicates right or bottom, 0.5 means center. 
1842  * If @use_align is %FALSE, the text scrolls the minimal distance to 
1843  * get the mark onscreen, possibly not scrolling at all. The effective 
1844  * screen for purposes of this function is reduced by a margin of size 
1845  * @within_margin.
1846  *
1847  * Note that this function uses the currently-computed height of the
1848  * lines in the text buffer. Line heights are computed in an idle 
1849  * handler; so this function may not have the desired effect if it's 
1850  * called before the height computations. To avoid oddness, consider 
1851  * using gtk_text_view_scroll_to_mark() which saves a point to be 
1852  * scrolled to after line validation.
1853  *
1854  * Return value: %TRUE if scrolling occurred
1855  **/
1856 gboolean
1857 gtk_text_view_scroll_to_iter (GtkTextView   *text_view,
1858                               GtkTextIter   *iter,
1859                               gdouble        within_margin,
1860                               gboolean       use_align,
1861                               gdouble        xalign,
1862                               gdouble        yalign)
1863 {
1864   GdkRectangle rect;
1865   GdkRectangle screen;
1866   gint screen_bottom;
1867   gint screen_right;
1868   gint scroll_dest;
1869   GtkWidget *widget;
1870   gboolean retval = FALSE;
1871   gint scroll_inc;
1872   gint screen_xoffset, screen_yoffset;
1873   gint current_x_scroll, current_y_scroll;
1874
1875   /* FIXME why don't we do the validate-at-scroll-destination thing
1876    * from flush_scroll in this function? I think it wasn't done before
1877    * because changed_handler was screwed up, but I could be wrong.
1878    */
1879   
1880   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
1881   g_return_val_if_fail (iter != NULL, FALSE);
1882   g_return_val_if_fail (within_margin >= 0.0 && within_margin < 0.5, FALSE);
1883   g_return_val_if_fail (xalign >= 0.0 && xalign <= 1.0, FALSE);
1884   g_return_val_if_fail (yalign >= 0.0 && yalign <= 1.0, FALSE);
1885   
1886   widget = GTK_WIDGET (text_view);
1887
1888   DV(g_print(G_STRLOC"\n"));
1889   
1890   gtk_text_layout_get_iter_location (text_view->priv->layout,
1891                                      iter,
1892                                      &rect);
1893
1894   DV (g_print (" target rect %d,%d  %d x %d\n", rect.x, rect.y, rect.width, rect.height));
1895   
1896   current_x_scroll = text_view->priv->xoffset;
1897   current_y_scroll = text_view->priv->yoffset;
1898
1899   screen.x = current_x_scroll;
1900   screen.y = current_y_scroll;
1901   screen.width = SCREEN_WIDTH (widget);
1902   screen.height = SCREEN_HEIGHT (widget);
1903   
1904   screen_xoffset = screen.width * within_margin;
1905   screen_yoffset = screen.height * within_margin;
1906   
1907   screen.x += screen_xoffset;
1908   screen.y += screen_yoffset;
1909   screen.width -= screen_xoffset * 2;
1910   screen.height -= screen_yoffset * 2;
1911
1912   /* paranoia check */
1913   if (screen.width < 1)
1914     screen.width = 1;
1915   if (screen.height < 1)
1916     screen.height = 1;
1917   
1918   /* The -1 here ensures that we leave enough space to draw the cursor
1919    * when this function is used for horizontal scrolling. 
1920    */
1921   screen_right = screen.x + screen.width - 1;
1922   screen_bottom = screen.y + screen.height;
1923   
1924   /* The alignment affects the point in the target character that we
1925    * choose to align. If we're doing right/bottom alignment, we align
1926    * the right/bottom edge of the character the mark is at; if we're
1927    * doing left/top we align the left/top edge of the character; if
1928    * we're doing center alignment we align the center of the
1929    * character.
1930    */
1931   
1932   /* Vertical scroll */
1933
1934   scroll_inc = 0;
1935   scroll_dest = current_y_scroll;
1936   
1937   if (use_align)
1938     {      
1939       scroll_dest = rect.y + (rect.height * yalign) - (screen.height * yalign);
1940       
1941       /* if scroll_dest < screen.y, we move a negative increment (up),
1942        * else a positive increment (down)
1943        */
1944       scroll_inc = scroll_dest - screen.y + screen_yoffset;
1945     }
1946   else
1947     {
1948       /* move minimum to get onscreen */
1949       if (rect.y < screen.y)
1950         {
1951           scroll_dest = rect.y;
1952           scroll_inc = scroll_dest - screen.y - screen_yoffset;
1953         }
1954       else if ((rect.y + rect.height) > screen_bottom)
1955         {
1956           scroll_dest = rect.y + rect.height;
1957           scroll_inc = scroll_dest - screen_bottom + screen_yoffset;
1958         }
1959     }  
1960   
1961   if (scroll_inc != 0)
1962     {
1963       gtk_adjustment_set_value (text_view->priv->vadjustment,
1964                                 current_y_scroll + scroll_inc);
1965
1966       DV (g_print (" vert increment %d\n", scroll_inc));
1967     }
1968
1969   /* Horizontal scroll */
1970   
1971   scroll_inc = 0;
1972   scroll_dest = current_x_scroll;
1973   
1974   if (use_align)
1975     {      
1976       scroll_dest = rect.x + (rect.width * xalign) - (screen.width * xalign);
1977
1978       /* if scroll_dest < screen.y, we move a negative increment (left),
1979        * else a positive increment (right)
1980        */
1981       scroll_inc = scroll_dest - screen.x + screen_xoffset;
1982     }
1983   else
1984     {
1985       /* move minimum to get onscreen */
1986       if (rect.x < screen.x)
1987         {
1988           scroll_dest = rect.x;
1989           scroll_inc = scroll_dest - screen.x - screen_xoffset;
1990         }
1991       else if ((rect.x + rect.width) > screen_right)
1992         {
1993           scroll_dest = rect.x + rect.width;
1994           scroll_inc = scroll_dest - screen_right + screen_xoffset;
1995         }
1996     }
1997   
1998   if (scroll_inc != 0)
1999     {
2000       gtk_adjustment_set_value (text_view->priv->hadjustment,
2001                                 current_x_scroll + scroll_inc);
2002
2003       DV (g_print (" horiz increment %d\n", scroll_inc));
2004     }
2005   
2006   retval = (current_y_scroll != gtk_adjustment_get_value (text_view->priv->vadjustment))
2007            || (current_x_scroll != gtk_adjustment_get_value (text_view->priv->hadjustment));
2008
2009   if (retval)
2010     {
2011       DV(g_print (">Actually scrolled ("G_STRLOC")\n"));
2012     }
2013   else
2014     {
2015       DV(g_print (">Didn't end up scrolling ("G_STRLOC")\n"));
2016     }
2017   
2018   return retval;
2019 }
2020
2021 static void
2022 free_pending_scroll (GtkTextPendingScroll *scroll)
2023 {
2024   if (!gtk_text_mark_get_deleted (scroll->mark))
2025     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (scroll->mark),
2026                                  scroll->mark);
2027   g_object_unref (scroll->mark);
2028   g_free (scroll);
2029 }
2030
2031 static void
2032 cancel_pending_scroll (GtkTextView *text_view)
2033 {
2034   if (text_view->priv->pending_scroll)
2035     {
2036       free_pending_scroll (text_view->priv->pending_scroll);
2037       text_view->priv->pending_scroll = NULL;
2038     }
2039 }
2040
2041 static void
2042 gtk_text_view_queue_scroll (GtkTextView   *text_view,
2043                             GtkTextMark   *mark,
2044                             gdouble        within_margin,
2045                             gboolean       use_align,
2046                             gdouble        xalign,
2047                             gdouble        yalign)
2048 {
2049   GtkTextIter iter;
2050   GtkTextPendingScroll *scroll;
2051
2052   DV(g_print(G_STRLOC"\n"));
2053   
2054   scroll = g_new (GtkTextPendingScroll, 1);
2055
2056   scroll->within_margin = within_margin;
2057   scroll->use_align = use_align;
2058   scroll->xalign = xalign;
2059   scroll->yalign = yalign;
2060   
2061   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, mark);
2062
2063   scroll->mark = gtk_text_buffer_create_mark (get_buffer (text_view),
2064                                               NULL,
2065                                               &iter,
2066                                               gtk_text_mark_get_left_gravity (mark));
2067
2068   g_object_ref (scroll->mark);
2069   
2070   cancel_pending_scroll (text_view);
2071
2072   text_view->priv->pending_scroll = scroll;
2073 }
2074
2075 static gboolean
2076 gtk_text_view_flush_scroll (GtkTextView *text_view)
2077 {
2078   GtkAllocation allocation;
2079   GtkTextIter iter;
2080   GtkTextPendingScroll *scroll;
2081   gboolean retval;
2082   GtkWidget *widget;
2083
2084   widget = GTK_WIDGET (text_view);
2085   
2086   DV(g_print(G_STRLOC"\n"));
2087   
2088   if (text_view->priv->pending_scroll == NULL)
2089     {
2090       DV (g_print ("in flush scroll, no pending scroll\n"));
2091       return FALSE;
2092     }
2093
2094   scroll = text_view->priv->pending_scroll;
2095
2096   /* avoid recursion */
2097   text_view->priv->pending_scroll = NULL;
2098   
2099   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, scroll->mark);
2100
2101   /* Validate area around the scroll destination, so the adjustment
2102    * can meaningfully point into that area. We must validate
2103    * enough area to be sure that after we scroll, everything onscreen
2104    * is valid; otherwise, validation will maintain the first para
2105    * in one place, but may push the target iter off the bottom of
2106    * the screen.
2107    */
2108   DV(g_print (">Validating scroll destination ("G_STRLOC")\n"));
2109   gtk_widget_get_allocation (widget, &allocation);
2110   gtk_text_layout_validate_yrange (text_view->priv->layout, &iter,
2111                                    -(allocation.height * 2),
2112                                    allocation.height * 2);
2113
2114   DV(g_print (">Done validating scroll destination ("G_STRLOC")\n"));
2115
2116   /* Ensure we have updated width/height */
2117   gtk_text_view_update_adjustments (text_view);
2118   
2119   retval = gtk_text_view_scroll_to_iter (text_view,
2120                                          &iter,
2121                                          scroll->within_margin,
2122                                          scroll->use_align,
2123                                          scroll->xalign,
2124                                          scroll->yalign);
2125
2126   free_pending_scroll (scroll);
2127
2128   return retval;
2129 }
2130
2131 static void
2132 gtk_text_view_update_adjustments (GtkTextView *text_view)
2133 {
2134   GtkTextViewPrivate *priv;
2135   gint width = 0, height = 0;
2136
2137   DV(g_print(">Updating adjustments ("G_STRLOC")\n"));
2138
2139   priv = text_view->priv;
2140
2141   if (priv->layout)
2142     gtk_text_layout_get_size (priv->layout, &width, &height);
2143
2144   /* Make room for the cursor after the last character in the widest line */
2145   width += SPACE_FOR_CURSOR;
2146
2147   if (priv->width != width || priv->height != height)
2148     {
2149       if (priv->width != width)
2150         priv->width_changed = TRUE;
2151
2152       priv->width = width;
2153       priv->height = height;
2154
2155       gtk_text_view_set_hadjustment_values (text_view);
2156       gtk_text_view_set_vadjustment_values (text_view);
2157     }
2158 }
2159
2160 static void
2161 gtk_text_view_update_layout_width (GtkTextView *text_view)
2162 {
2163   DV(g_print(">Updating layout width ("G_STRLOC")\n"));
2164   
2165   gtk_text_view_ensure_layout (text_view);
2166
2167   gtk_text_layout_set_screen_width (text_view->priv->layout,
2168                                     MAX (1, SCREEN_WIDTH (text_view) - SPACE_FOR_CURSOR));
2169 }
2170
2171 static void
2172 gtk_text_view_update_im_spot_location (GtkTextView *text_view)
2173 {
2174   GdkRectangle area;
2175
2176   if (text_view->priv->layout == NULL)
2177     return;
2178   
2179   gtk_text_view_get_cursor_locations (text_view, NULL, &area, NULL);
2180
2181   area.x -= text_view->priv->xoffset;
2182   area.y -= text_view->priv->yoffset;
2183     
2184   /* Width returned by Pango indicates direction of cursor,
2185    * by its sign more than the size of cursor.
2186    */
2187   area.width = 0;
2188
2189   gtk_im_context_set_cursor_location (text_view->priv->im_context, &area);
2190 }
2191
2192 static gboolean
2193 do_update_im_spot_location (gpointer text_view)
2194 {
2195   GtkTextViewPrivate *priv;
2196
2197   priv = GTK_TEXT_VIEW (text_view)->priv;
2198   priv->im_spot_idle = 0;
2199
2200   gtk_text_view_update_im_spot_location (text_view);
2201   return FALSE;
2202 }
2203
2204 static void
2205 queue_update_im_spot_location (GtkTextView *text_view)
2206 {
2207   GtkTextViewPrivate *priv;
2208
2209   priv = text_view->priv;
2210
2211   /* Use priority a little higher than GTK_TEXT_VIEW_PRIORITY_VALIDATE,
2212    * so we don't wait until the entire buffer has been validated. */
2213   if (!priv->im_spot_idle)
2214     priv->im_spot_idle = gdk_threads_add_idle_full (GTK_TEXT_VIEW_PRIORITY_VALIDATE - 1,
2215                                                     do_update_im_spot_location,
2216                                                     text_view,
2217                                                     NULL);
2218 }
2219
2220 static void
2221 flush_update_im_spot_location (GtkTextView *text_view)
2222 {
2223   GtkTextViewPrivate *priv;
2224
2225   priv = text_view->priv;
2226
2227   if (priv->im_spot_idle)
2228     {
2229       g_source_remove (priv->im_spot_idle);
2230       priv->im_spot_idle = 0;
2231       gtk_text_view_update_im_spot_location (text_view);
2232     }
2233 }
2234
2235 /**
2236  * gtk_text_view_scroll_to_mark:
2237  * @text_view: a #GtkTextView
2238  * @mark: a #GtkTextMark
2239  * @within_margin: margin as a [0.0,0.5) fraction of screen size
2240  * @use_align: whether to use alignment arguments (if %FALSE, just 
2241  *    get the mark onscreen)
2242  * @xalign: horizontal alignment of mark within visible area
2243  * @yalign: vertical alignment of mark within visible area
2244  *
2245  * Scrolls @text_view so that @mark is on the screen in the position
2246  * indicated by @xalign and @yalign. An alignment of 0.0 indicates
2247  * left or top, 1.0 indicates right or bottom, 0.5 means center. 
2248  * If @use_align is %FALSE, the text scrolls the minimal distance to 
2249  * get the mark onscreen, possibly not scrolling at all. The effective 
2250  * screen for purposes of this function is reduced by a margin of size 
2251  * @within_margin.
2252  **/
2253 void
2254 gtk_text_view_scroll_to_mark (GtkTextView *text_view,
2255                               GtkTextMark *mark,
2256                               gdouble      within_margin,
2257                               gboolean     use_align,
2258                               gdouble      xalign,
2259                               gdouble      yalign)
2260 {  
2261   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2262   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
2263   g_return_if_fail (within_margin >= 0.0 && within_margin < 0.5);
2264   g_return_if_fail (xalign >= 0.0 && xalign <= 1.0);
2265   g_return_if_fail (yalign >= 0.0 && yalign <= 1.0);
2266
2267   /* We need to verify that the buffer contains the mark, otherwise this
2268    * can lead to data structure corruption later on.
2269    */
2270   g_return_if_fail (get_buffer (text_view) == gtk_text_mark_get_buffer (mark));
2271
2272   gtk_text_view_queue_scroll (text_view, mark,
2273                               within_margin,
2274                               use_align,
2275                               xalign,
2276                               yalign);
2277
2278   /* If no validation is pending, we need to go ahead and force an
2279    * immediate scroll.
2280    */
2281   if (text_view->priv->layout &&
2282       gtk_text_layout_is_valid (text_view->priv->layout))
2283     gtk_text_view_flush_scroll (text_view);
2284 }
2285
2286 /**
2287  * gtk_text_view_scroll_mark_onscreen:
2288  * @text_view: a #GtkTextView
2289  * @mark: a mark in the buffer for @text_view
2290  * 
2291  * Scrolls @text_view the minimum distance such that @mark is contained
2292  * within the visible area of the widget.
2293  **/
2294 void
2295 gtk_text_view_scroll_mark_onscreen (GtkTextView *text_view,
2296                                     GtkTextMark *mark)
2297 {
2298   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2299   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
2300
2301   /* We need to verify that the buffer contains the mark, otherwise this
2302    * can lead to data structure corruption later on.
2303    */
2304   g_return_if_fail (get_buffer (text_view) == gtk_text_mark_get_buffer (mark));
2305
2306   gtk_text_view_scroll_to_mark (text_view, mark, 0.0, FALSE, 0.0, 0.0);
2307 }
2308
2309 static gboolean
2310 clamp_iter_onscreen (GtkTextView *text_view, GtkTextIter *iter)
2311 {
2312   GdkRectangle visible_rect;
2313   gtk_text_view_get_visible_rect (text_view, &visible_rect);
2314
2315   return gtk_text_layout_clamp_iter_to_vrange (text_view->priv->layout, iter,
2316                                                visible_rect.y,
2317                                                visible_rect.y + visible_rect.height);
2318 }
2319
2320 /**
2321  * gtk_text_view_move_mark_onscreen:
2322  * @text_view: a #GtkTextView
2323  * @mark: a #GtkTextMark
2324  *
2325  * Moves a mark within the buffer so that it's
2326  * located within the currently-visible text area.
2327  *
2328  * Return value: %TRUE if the mark moved (wasn't already onscreen)
2329  **/
2330 gboolean
2331 gtk_text_view_move_mark_onscreen (GtkTextView *text_view,
2332                                   GtkTextMark *mark)
2333 {
2334   GtkTextIter iter;
2335
2336   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2337   g_return_val_if_fail (mark != NULL, FALSE);
2338
2339   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, mark);
2340
2341   if (clamp_iter_onscreen (text_view, &iter))
2342     {
2343       gtk_text_buffer_move_mark (get_buffer (text_view), mark, &iter);
2344       return TRUE;
2345     }
2346   else
2347     return FALSE;
2348 }
2349
2350 /**
2351  * gtk_text_view_get_visible_rect:
2352  * @text_view: a #GtkTextView
2353  * @visible_rect: (out): rectangle to fill
2354  *
2355  * Fills @visible_rect with the currently-visible
2356  * region of the buffer, in buffer coordinates. Convert to window coordinates
2357  * with gtk_text_view_buffer_to_window_coords().
2358  **/
2359 void
2360 gtk_text_view_get_visible_rect (GtkTextView  *text_view,
2361                                 GdkRectangle *visible_rect)
2362 {
2363   GtkWidget *widget;
2364
2365   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2366
2367   widget = GTK_WIDGET (text_view);
2368
2369   if (visible_rect)
2370     {
2371       visible_rect->x = text_view->priv->xoffset;
2372       visible_rect->y = text_view->priv->yoffset;
2373       visible_rect->width = SCREEN_WIDTH (widget);
2374       visible_rect->height = SCREEN_HEIGHT (widget);
2375
2376       DV(g_print(" visible rect: %d,%d %d x %d\n",
2377                  visible_rect->x,
2378                  visible_rect->y,
2379                  visible_rect->width,
2380                  visible_rect->height));
2381     }
2382 }
2383
2384 /**
2385  * gtk_text_view_set_wrap_mode:
2386  * @text_view: a #GtkTextView
2387  * @wrap_mode: a #GtkWrapMode
2388  *
2389  * Sets the line wrapping for the view.
2390  **/
2391 void
2392 gtk_text_view_set_wrap_mode (GtkTextView *text_view,
2393                              GtkWrapMode  wrap_mode)
2394 {
2395   GtkTextViewPrivate *priv;
2396
2397   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2398
2399   priv = text_view->priv;
2400
2401   if (priv->wrap_mode != wrap_mode)
2402     {
2403       priv->wrap_mode = wrap_mode;
2404
2405       if (priv->layout && priv->layout->default_style)
2406         {
2407           priv->layout->default_style->wrap_mode = wrap_mode;
2408           gtk_text_layout_default_style_changed (priv->layout);
2409         }
2410     }
2411
2412   g_object_notify (G_OBJECT (text_view), "wrap-mode");
2413 }
2414
2415 /**
2416  * gtk_text_view_get_wrap_mode:
2417  * @text_view: a #GtkTextView
2418  *
2419  * Gets the line wrapping for the view.
2420  *
2421  * Return value: the line wrap setting
2422  **/
2423 GtkWrapMode
2424 gtk_text_view_get_wrap_mode (GtkTextView *text_view)
2425 {
2426   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_WRAP_NONE);
2427
2428   return text_view->priv->wrap_mode;
2429 }
2430
2431 /**
2432  * gtk_text_view_set_editable:
2433  * @text_view: a #GtkTextView
2434  * @setting: whether it's editable
2435  *
2436  * Sets the default editability of the #GtkTextView. You can override
2437  * this default setting with tags in the buffer, using the "editable"
2438  * attribute of tags.
2439  **/
2440 void
2441 gtk_text_view_set_editable (GtkTextView *text_view,
2442                             gboolean     setting)
2443 {
2444   GtkTextViewPrivate *priv;
2445
2446   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2447
2448   priv = text_view->priv;
2449   setting = setting != FALSE;
2450
2451   if (priv->editable != setting)
2452     {
2453       if (!setting)
2454         {
2455           gtk_text_view_reset_im_context(text_view);
2456           if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
2457             gtk_im_context_focus_out (priv->im_context);
2458         }
2459
2460       priv->editable = setting;
2461
2462       if (setting && gtk_widget_has_focus (GTK_WIDGET (text_view)))
2463         gtk_im_context_focus_in (priv->im_context);
2464
2465       if (priv->layout && priv->layout->default_style)
2466         {
2467           gtk_text_layout_set_overwrite_mode (priv->layout,
2468                                               priv->overwrite_mode && priv->editable);
2469           priv->layout->default_style->editable = priv->editable;
2470           gtk_text_layout_default_style_changed (priv->layout);
2471         }
2472
2473       g_object_notify (G_OBJECT (text_view), "editable");
2474     }
2475 }
2476
2477 /**
2478  * gtk_text_view_get_editable:
2479  * @text_view: a #GtkTextView
2480  *
2481  * Returns the default editability of the #GtkTextView. Tags in the
2482  * buffer may override this setting for some ranges of text.
2483  *
2484  * Return value: whether text is editable by default
2485  **/
2486 gboolean
2487 gtk_text_view_get_editable (GtkTextView *text_view)
2488 {
2489   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2490
2491   return text_view->priv->editable;
2492 }
2493
2494 /**
2495  * gtk_text_view_set_pixels_above_lines:
2496  * @text_view: a #GtkTextView
2497  * @pixels_above_lines: pixels above paragraphs
2498  * 
2499  * Sets the default number of blank pixels above paragraphs in @text_view.
2500  * Tags in the buffer for @text_view may override the defaults.
2501  **/
2502 void
2503 gtk_text_view_set_pixels_above_lines (GtkTextView *text_view,
2504                                       gint         pixels_above_lines)
2505 {
2506   GtkTextViewPrivate *priv;
2507
2508   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2509
2510   priv = text_view->priv;
2511
2512   if (priv->pixels_above_lines != pixels_above_lines)
2513     {
2514       priv->pixels_above_lines = pixels_above_lines;
2515
2516       if (priv->layout && priv->layout->default_style)
2517         {
2518           priv->layout->default_style->pixels_above_lines = pixels_above_lines;
2519           gtk_text_layout_default_style_changed (priv->layout);
2520         }
2521
2522       g_object_notify (G_OBJECT (text_view), "pixels-above-lines");
2523     }
2524 }
2525
2526 /**
2527  * gtk_text_view_get_pixels_above_lines:
2528  * @text_view: a #GtkTextView
2529  * 
2530  * Gets the default number of pixels to put above paragraphs.
2531  * 
2532  * Return value: default number of pixels above paragraphs
2533  **/
2534 gint
2535 gtk_text_view_get_pixels_above_lines (GtkTextView *text_view)
2536 {
2537   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2538
2539   return text_view->priv->pixels_above_lines;
2540 }
2541
2542 /**
2543  * gtk_text_view_set_pixels_below_lines:
2544  * @text_view: a #GtkTextView
2545  * @pixels_below_lines: pixels below paragraphs 
2546  *
2547  * Sets the default number of pixels of blank space
2548  * to put below paragraphs in @text_view. May be overridden
2549  * by tags applied to @text_view's buffer. 
2550  **/
2551 void
2552 gtk_text_view_set_pixels_below_lines (GtkTextView *text_view,
2553                                       gint         pixels_below_lines)
2554 {
2555   GtkTextViewPrivate *priv;
2556
2557   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2558
2559   priv = text_view->priv;
2560
2561   if (priv->pixels_below_lines != pixels_below_lines)
2562     {
2563       priv->pixels_below_lines = pixels_below_lines;
2564
2565       if (priv->layout && priv->layout->default_style)
2566         {
2567           priv->layout->default_style->pixels_below_lines = pixels_below_lines;
2568           gtk_text_layout_default_style_changed (priv->layout);
2569         }
2570
2571       g_object_notify (G_OBJECT (text_view), "pixels-below-lines");
2572     }
2573 }
2574
2575 /**
2576  * gtk_text_view_get_pixels_below_lines:
2577  * @text_view: a #GtkTextView
2578  * 
2579  * Gets the value set by gtk_text_view_set_pixels_below_lines().
2580  * 
2581  * Return value: default number of blank pixels below paragraphs
2582  **/
2583 gint
2584 gtk_text_view_get_pixels_below_lines (GtkTextView *text_view)
2585 {
2586   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2587
2588   return text_view->priv->pixels_below_lines;
2589 }
2590
2591 /**
2592  * gtk_text_view_set_pixels_inside_wrap:
2593  * @text_view: a #GtkTextView
2594  * @pixels_inside_wrap: default number of pixels between wrapped lines
2595  *
2596  * Sets the default number of pixels of blank space to leave between
2597  * display/wrapped lines within a paragraph. May be overridden by
2598  * tags in @text_view's buffer.
2599  **/
2600 void
2601 gtk_text_view_set_pixels_inside_wrap (GtkTextView *text_view,
2602                                       gint         pixels_inside_wrap)
2603 {
2604   GtkTextViewPrivate *priv;
2605
2606   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2607
2608   priv = text_view->priv;
2609
2610   if (priv->pixels_inside_wrap != pixels_inside_wrap)
2611     {
2612       priv->pixels_inside_wrap = pixels_inside_wrap;
2613
2614       if (priv->layout && priv->layout->default_style)
2615         {
2616           priv->layout->default_style->pixels_inside_wrap = pixels_inside_wrap;
2617           gtk_text_layout_default_style_changed (priv->layout);
2618         }
2619
2620       g_object_notify (G_OBJECT (text_view), "pixels-inside-wrap");
2621     }
2622 }
2623
2624 /**
2625  * gtk_text_view_get_pixels_inside_wrap:
2626  * @text_view: a #GtkTextView
2627  * 
2628  * Gets the value set by gtk_text_view_set_pixels_inside_wrap().
2629  * 
2630  * Return value: default number of pixels of blank space between wrapped lines
2631  **/
2632 gint
2633 gtk_text_view_get_pixels_inside_wrap (GtkTextView *text_view)
2634 {
2635   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2636
2637   return text_view->priv->pixels_inside_wrap;
2638 }
2639
2640 /**
2641  * gtk_text_view_set_justification:
2642  * @text_view: a #GtkTextView
2643  * @justification: justification
2644  *
2645  * Sets the default justification of text in @text_view.
2646  * Tags in the view's buffer may override the default.
2647  * 
2648  **/
2649 void
2650 gtk_text_view_set_justification (GtkTextView     *text_view,
2651                                  GtkJustification justification)
2652 {
2653   GtkTextViewPrivate *priv;
2654
2655   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2656
2657   priv = text_view->priv;
2658
2659   if (priv->justify != justification)
2660     {
2661       priv->justify = justification;
2662
2663       if (priv->layout && priv->layout->default_style)
2664         {
2665           priv->layout->default_style->justification = justification;
2666           gtk_text_layout_default_style_changed (priv->layout);
2667         }
2668
2669       g_object_notify (G_OBJECT (text_view), "justification");
2670     }
2671 }
2672
2673 /**
2674  * gtk_text_view_get_justification:
2675  * @text_view: a #GtkTextView
2676  * 
2677  * Gets the default justification of paragraphs in @text_view.
2678  * Tags in the buffer may override the default.
2679  * 
2680  * Return value: default justification
2681  **/
2682 GtkJustification
2683 gtk_text_view_get_justification (GtkTextView *text_view)
2684 {
2685   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_JUSTIFY_LEFT);
2686
2687   return text_view->priv->justify;
2688 }
2689
2690 /**
2691  * gtk_text_view_set_left_margin:
2692  * @text_view: a #GtkTextView
2693  * @left_margin: left margin in pixels
2694  * 
2695  * Sets the default left margin for text in @text_view.
2696  * Tags in the buffer may override the default.
2697  **/
2698 void
2699 gtk_text_view_set_left_margin (GtkTextView *text_view,
2700                                gint         left_margin)
2701 {
2702   GtkTextViewPrivate *priv;
2703
2704   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2705
2706   priv = text_view->priv;
2707
2708   if (priv->left_margin != left_margin)
2709     {
2710       priv->left_margin = left_margin;
2711
2712       if (priv->layout && priv->layout->default_style)
2713         {
2714           priv->layout->default_style->left_margin = left_margin;
2715           gtk_text_layout_default_style_changed (priv->layout);
2716         }
2717
2718       g_object_notify (G_OBJECT (text_view), "left-margin");
2719     }
2720 }
2721
2722 /**
2723  * gtk_text_view_get_left_margin:
2724  * @text_view: a #GtkTextView
2725  * 
2726  * Gets the default left margin size of paragraphs in the @text_view.
2727  * Tags in the buffer may override the default.
2728  * 
2729  * Return value: left margin in pixels
2730  **/
2731 gint
2732 gtk_text_view_get_left_margin (GtkTextView *text_view)
2733 {
2734   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2735
2736   return text_view->priv->left_margin;
2737 }
2738
2739 /**
2740  * gtk_text_view_set_right_margin:
2741  * @text_view: a #GtkTextView
2742  * @right_margin: right margin in pixels
2743  *
2744  * Sets the default right margin for text in the text view.
2745  * Tags in the buffer may override the default.
2746  **/
2747 void
2748 gtk_text_view_set_right_margin (GtkTextView *text_view,
2749                                 gint         right_margin)
2750 {
2751   GtkTextViewPrivate *priv = text_view->priv;
2752
2753   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2754
2755   if (priv->right_margin != right_margin)
2756     {
2757       priv->right_margin = right_margin;
2758
2759       if (priv->layout && priv->layout->default_style)
2760         {
2761           priv->layout->default_style->right_margin = right_margin;
2762           gtk_text_layout_default_style_changed (priv->layout);
2763         }
2764
2765       g_object_notify (G_OBJECT (text_view), "right-margin");
2766     }
2767 }
2768
2769 /**
2770  * gtk_text_view_get_right_margin:
2771  * @text_view: a #GtkTextView
2772  * 
2773  * Gets the default right margin for text in @text_view. Tags
2774  * in the buffer may override the default.
2775  * 
2776  * Return value: right margin in pixels
2777  **/
2778 gint
2779 gtk_text_view_get_right_margin (GtkTextView *text_view)
2780 {
2781   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2782
2783   return text_view->priv->right_margin;
2784 }
2785
2786 /**
2787  * gtk_text_view_set_indent:
2788  * @text_view: a #GtkTextView
2789  * @indent: indentation in pixels
2790  *
2791  * Sets the default indentation for paragraphs in @text_view.
2792  * Tags in the buffer may override the default.
2793  **/
2794 void
2795 gtk_text_view_set_indent (GtkTextView *text_view,
2796                           gint         indent)
2797 {
2798   GtkTextViewPrivate *priv;
2799
2800   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2801
2802   priv = text_view->priv;
2803
2804   if (priv->indent != indent)
2805     {
2806       priv->indent = indent;
2807
2808       if (priv->layout && priv->layout->default_style)
2809         {
2810           priv->layout->default_style->indent = indent;
2811           gtk_text_layout_default_style_changed (priv->layout);
2812         }
2813
2814       g_object_notify (G_OBJECT (text_view), "indent");
2815     }
2816 }
2817
2818 /**
2819  * gtk_text_view_get_indent:
2820  * @text_view: a #GtkTextView
2821  * 
2822  * Gets the default indentation of paragraphs in @text_view.
2823  * Tags in the view's buffer may override the default.
2824  * The indentation may be negative.
2825  * 
2826  * Return value: number of pixels of indentation
2827  **/
2828 gint
2829 gtk_text_view_get_indent (GtkTextView *text_view)
2830 {
2831   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2832
2833   return text_view->priv->indent;
2834 }
2835
2836 /**
2837  * gtk_text_view_set_tabs:
2838  * @text_view: a #GtkTextView
2839  * @tabs: tabs as a #PangoTabArray
2840  *
2841  * Sets the default tab stops for paragraphs in @text_view.
2842  * Tags in the buffer may override the default.
2843  **/
2844 void
2845 gtk_text_view_set_tabs (GtkTextView   *text_view,
2846                         PangoTabArray *tabs)
2847 {
2848   GtkTextViewPrivate *priv;
2849
2850   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2851
2852   priv = text_view->priv;
2853
2854   if (priv->tabs)
2855     pango_tab_array_free (priv->tabs);
2856
2857   priv->tabs = tabs ? pango_tab_array_copy (tabs) : NULL;
2858
2859   if (priv->layout && priv->layout->default_style)
2860     {
2861       /* some unkosher futzing in internal struct details... */
2862       if (priv->layout->default_style->tabs)
2863         pango_tab_array_free (priv->layout->default_style->tabs);
2864
2865       priv->layout->default_style->tabs =
2866         priv->tabs ? pango_tab_array_copy (priv->tabs) : NULL;
2867
2868       gtk_text_layout_default_style_changed (priv->layout);
2869     }
2870
2871   g_object_notify (G_OBJECT (text_view), "tabs");
2872 }
2873
2874 /**
2875  * gtk_text_view_get_tabs:
2876  * @text_view: a #GtkTextView
2877  * 
2878  * Gets the default tabs for @text_view. Tags in the buffer may
2879  * override the defaults. The returned array will be %NULL if
2880  * "standard" (8-space) tabs are used. Free the return value
2881  * with pango_tab_array_free().
2882  * 
2883  * Return value: copy of default tab array, or %NULL if "standard" 
2884  *    tabs are used; must be freed with pango_tab_array_free().
2885  **/
2886 PangoTabArray*
2887 gtk_text_view_get_tabs (GtkTextView *text_view)
2888 {
2889   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
2890
2891   return text_view->priv->tabs ? pango_tab_array_copy (text_view->priv->tabs) : NULL;
2892 }
2893
2894 static void
2895 gtk_text_view_toggle_cursor_visible (GtkTextView *text_view)
2896 {
2897   gtk_text_view_set_cursor_visible (text_view, !text_view->priv->cursor_visible);
2898 }
2899
2900 /**
2901  * gtk_text_view_set_cursor_visible:
2902  * @text_view: a #GtkTextView
2903  * @setting: whether to show the insertion cursor
2904  *
2905  * Toggles whether the insertion point is displayed. A buffer with no editable
2906  * text probably shouldn't have a visible cursor, so you may want to turn
2907  * the cursor off.
2908  **/
2909 void
2910 gtk_text_view_set_cursor_visible (GtkTextView *text_view,
2911                                   gboolean     setting)
2912 {
2913   GtkTextViewPrivate *priv;
2914
2915   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2916
2917   priv = text_view->priv;
2918   setting = (setting != FALSE);
2919
2920   if (priv->cursor_visible != setting)
2921     {
2922       priv->cursor_visible = setting;
2923
2924       if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
2925         {
2926           if (priv->layout)
2927             {
2928               gtk_text_layout_set_cursor_visible (priv->layout, setting);
2929               gtk_text_view_check_cursor_blink (text_view);
2930             }
2931         }
2932
2933       g_object_notify (G_OBJECT (text_view), "cursor-visible");
2934     }
2935 }
2936
2937 /**
2938  * gtk_text_view_get_cursor_visible:
2939  * @text_view: a #GtkTextView
2940  *
2941  * Find out whether the cursor is being displayed.
2942  *
2943  * Return value: whether the insertion mark is visible
2944  **/
2945 gboolean
2946 gtk_text_view_get_cursor_visible (GtkTextView *text_view)
2947 {
2948   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2949
2950   return text_view->priv->cursor_visible;
2951 }
2952
2953
2954 /**
2955  * gtk_text_view_place_cursor_onscreen:
2956  * @text_view: a #GtkTextView
2957  *
2958  * Moves the cursor to the currently visible region of the
2959  * buffer, it it isn't there already.
2960  *
2961  * Return value: %TRUE if the cursor had to be moved.
2962  **/
2963 gboolean
2964 gtk_text_view_place_cursor_onscreen (GtkTextView *text_view)
2965 {
2966   GtkTextIter insert;
2967
2968   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2969
2970   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
2971                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
2972
2973   if (clamp_iter_onscreen (text_view, &insert))
2974     {
2975       gtk_text_buffer_place_cursor (get_buffer (text_view), &insert);
2976       return TRUE;
2977     }
2978   else
2979     return FALSE;
2980 }
2981
2982 static void
2983 gtk_text_view_remove_validate_idles (GtkTextView *text_view)
2984 {
2985   GtkTextViewPrivate *priv = text_view->priv;
2986
2987   if (priv->first_validate_idle != 0)
2988     {
2989       DV (g_print ("Removing first validate idle: %s\n", G_STRLOC));
2990       g_source_remove (priv->first_validate_idle);
2991       priv->first_validate_idle = 0;
2992     }
2993
2994   if (priv->incremental_validate_idle != 0)
2995     {
2996       g_source_remove (priv->incremental_validate_idle);
2997       priv->incremental_validate_idle = 0;
2998     }
2999 }
3000
3001 static void
3002 gtk_text_view_destroy (GtkWidget *widget)
3003 {
3004   GtkTextView *text_view;
3005   GtkTextViewPrivate *priv;
3006
3007   text_view = GTK_TEXT_VIEW (widget);
3008   priv = text_view->priv;
3009
3010   gtk_text_view_remove_validate_idles (text_view);
3011   gtk_text_view_set_buffer (text_view, NULL);
3012   gtk_text_view_destroy_layout (text_view);
3013
3014   if (text_view->priv->scroll_timeout)
3015     {
3016       g_source_remove (text_view->priv->scroll_timeout);
3017       text_view->priv->scroll_timeout = 0;
3018     }
3019
3020   if (priv->im_spot_idle)
3021     {
3022       g_source_remove (priv->im_spot_idle);
3023       priv->im_spot_idle = 0;
3024     }
3025
3026   GTK_WIDGET_CLASS (gtk_text_view_parent_class)->destroy (widget);
3027 }
3028
3029 static void
3030 gtk_text_view_finalize (GObject *object)
3031 {
3032   GtkTextView *text_view;
3033   GtkTextViewPrivate *priv;
3034
3035   text_view = GTK_TEXT_VIEW (object);
3036   priv = text_view->priv;
3037
3038   gtk_text_view_destroy_layout (text_view);
3039   gtk_text_view_set_buffer (text_view, NULL);
3040
3041   /* at this point, no "notify::buffer" handler should recreate the buffer. */
3042   g_assert (priv->buffer == NULL);
3043   
3044   cancel_pending_scroll (text_view);
3045
3046   if (priv->tabs)
3047     pango_tab_array_free (priv->tabs);
3048   
3049   if (priv->hadjustment)
3050     g_object_unref (priv->hadjustment);
3051   if (priv->vadjustment)
3052     g_object_unref (priv->vadjustment);
3053
3054   text_window_free (priv->text_window);
3055
3056   if (priv->left_window)
3057     text_window_free (priv->left_window);
3058
3059   if (priv->top_window)
3060     text_window_free (priv->top_window);
3061
3062   if (priv->right_window)
3063     text_window_free (priv->right_window);
3064
3065   if (priv->bottom_window)
3066     text_window_free (priv->bottom_window);
3067
3068   g_object_unref (priv->im_context);
3069
3070   g_free (priv->im_module);
3071
3072   G_OBJECT_CLASS (gtk_text_view_parent_class)->finalize (object);
3073 }
3074
3075 static void
3076 gtk_text_view_set_property (GObject         *object,
3077                             guint            prop_id,
3078                             const GValue    *value,
3079                             GParamSpec      *pspec)
3080 {
3081   GtkTextView *text_view;
3082   GtkTextViewPrivate *priv;
3083
3084   text_view = GTK_TEXT_VIEW (object);
3085   priv = text_view->priv;
3086
3087   switch (prop_id)
3088     {
3089     case PROP_PIXELS_ABOVE_LINES:
3090       gtk_text_view_set_pixels_above_lines (text_view, g_value_get_int (value));
3091       break;
3092
3093     case PROP_PIXELS_BELOW_LINES:
3094       gtk_text_view_set_pixels_below_lines (text_view, g_value_get_int (value));
3095       break;
3096
3097     case PROP_PIXELS_INSIDE_WRAP:
3098       gtk_text_view_set_pixels_inside_wrap (text_view, g_value_get_int (value));
3099       break;
3100
3101     case PROP_EDITABLE:
3102       gtk_text_view_set_editable (text_view, g_value_get_boolean (value));
3103       break;
3104
3105     case PROP_WRAP_MODE:
3106       gtk_text_view_set_wrap_mode (text_view, g_value_get_enum (value));
3107       break;
3108       
3109     case PROP_JUSTIFICATION:
3110       gtk_text_view_set_justification (text_view, g_value_get_enum (value));
3111       break;
3112
3113     case PROP_LEFT_MARGIN:
3114       gtk_text_view_set_left_margin (text_view, g_value_get_int (value));
3115       break;
3116
3117     case PROP_RIGHT_MARGIN:
3118       gtk_text_view_set_right_margin (text_view, g_value_get_int (value));
3119       break;
3120
3121     case PROP_INDENT:
3122       gtk_text_view_set_indent (text_view, g_value_get_int (value));
3123       break;
3124
3125     case PROP_TABS:
3126       gtk_text_view_set_tabs (text_view, g_value_get_boxed (value));
3127       break;
3128
3129     case PROP_CURSOR_VISIBLE:
3130       gtk_text_view_set_cursor_visible (text_view, g_value_get_boolean (value));
3131       break;
3132
3133     case PROP_OVERWRITE:
3134       gtk_text_view_set_overwrite (text_view, g_value_get_boolean (value));
3135       break;
3136
3137     case PROP_BUFFER:
3138       gtk_text_view_set_buffer (text_view, GTK_TEXT_BUFFER (g_value_get_object (value)));
3139       break;
3140
3141     case PROP_ACCEPTS_TAB:
3142       gtk_text_view_set_accepts_tab (text_view, g_value_get_boolean (value));
3143       break;
3144       
3145     case PROP_IM_MODULE:
3146       g_free (priv->im_module);
3147       priv->im_module = g_value_dup_string (value);
3148       if (GTK_IS_IM_MULTICONTEXT (priv->im_context))
3149         gtk_im_multicontext_set_context_id (GTK_IM_MULTICONTEXT (priv->im_context), priv->im_module);
3150       break;
3151
3152     case PROP_HADJUSTMENT:
3153       gtk_text_view_set_hadjustment (text_view, g_value_get_object (value));
3154       break;
3155
3156     case PROP_VADJUSTMENT:
3157       gtk_text_view_set_vadjustment (text_view, g_value_get_object (value));
3158       break;
3159
3160     case PROP_HSCROLL_POLICY:
3161       priv->hscroll_policy = g_value_get_enum (value);
3162       gtk_widget_queue_resize (GTK_WIDGET (text_view));
3163       break;
3164
3165     case PROP_VSCROLL_POLICY:
3166       priv->vscroll_policy = g_value_get_enum (value);
3167       gtk_widget_queue_resize (GTK_WIDGET (text_view));
3168       break;
3169
3170     default:
3171       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3172       break;
3173     }
3174 }
3175
3176 static void
3177 gtk_text_view_get_property (GObject         *object,
3178                             guint            prop_id,
3179                             GValue          *value,
3180                             GParamSpec      *pspec)
3181 {
3182   GtkTextView *text_view;
3183   GtkTextViewPrivate *priv;
3184
3185   text_view = GTK_TEXT_VIEW (object);
3186   priv = text_view->priv;
3187
3188   switch (prop_id)
3189     {
3190     case PROP_PIXELS_ABOVE_LINES:
3191       g_value_set_int (value, priv->pixels_above_lines);
3192       break;
3193
3194     case PROP_PIXELS_BELOW_LINES:
3195       g_value_set_int (value, priv->pixels_below_lines);
3196       break;
3197
3198     case PROP_PIXELS_INSIDE_WRAP:
3199       g_value_set_int (value, priv->pixels_inside_wrap);
3200       break;
3201
3202     case PROP_EDITABLE:
3203       g_value_set_boolean (value, priv->editable);
3204       break;
3205       
3206     case PROP_WRAP_MODE:
3207       g_value_set_enum (value, priv->wrap_mode);
3208       break;
3209
3210     case PROP_JUSTIFICATION:
3211       g_value_set_enum (value, priv->justify);
3212       break;
3213
3214     case PROP_LEFT_MARGIN:
3215       g_value_set_int (value, priv->left_margin);
3216       break;
3217
3218     case PROP_RIGHT_MARGIN:
3219       g_value_set_int (value, priv->right_margin);
3220       break;
3221
3222     case PROP_INDENT:
3223       g_value_set_int (value, priv->indent);
3224       break;
3225
3226     case PROP_TABS:
3227       g_value_set_boxed (value, priv->tabs);
3228       break;
3229
3230     case PROP_CURSOR_VISIBLE:
3231       g_value_set_boolean (value, priv->cursor_visible);
3232       break;
3233
3234     case PROP_BUFFER:
3235       g_value_set_object (value, get_buffer (text_view));
3236       break;
3237
3238     case PROP_OVERWRITE:
3239       g_value_set_boolean (value, priv->overwrite_mode);
3240       break;
3241
3242     case PROP_ACCEPTS_TAB:
3243       g_value_set_boolean (value, priv->accepts_tab);
3244       break;
3245       
3246     case PROP_IM_MODULE:
3247       g_value_set_string (value, priv->im_module);
3248       break;
3249
3250     case PROP_HADJUSTMENT:
3251       g_value_set_object (value, priv->hadjustment);
3252       break;
3253
3254     case PROP_VADJUSTMENT:
3255       g_value_set_object (value, priv->vadjustment);
3256       break;
3257
3258     case PROP_HSCROLL_POLICY:
3259       g_value_set_enum (value, priv->hscroll_policy);
3260       break;
3261
3262     case PROP_VSCROLL_POLICY:
3263       g_value_set_enum (value, priv->vscroll_policy);
3264       break;
3265
3266     default:
3267       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3268       break;
3269     }
3270 }
3271
3272 static void
3273 gtk_text_view_size_request (GtkWidget      *widget,
3274                             GtkRequisition *requisition)
3275 {
3276   GtkTextView *text_view;
3277   GtkTextViewPrivate *priv;
3278   GSList *tmp_list;
3279   gint focus_edge_width;
3280   gint focus_width;
3281   guint border_width;
3282   gboolean interior_focus;
3283
3284   text_view = GTK_TEXT_VIEW (widget);
3285   priv = text_view->priv;
3286
3287   gtk_widget_style_get (widget,
3288                         "interior-focus", &interior_focus,
3289                         "focus-line-width", &focus_width,
3290                         NULL);
3291
3292   if (interior_focus)
3293     focus_edge_width = 0;
3294   else
3295     focus_edge_width = focus_width;
3296
3297   if (priv->layout)
3298     {
3299       priv->text_window->requisition.width = priv->layout->width;
3300       priv->text_window->requisition.height = priv->layout->height;
3301     }
3302   else
3303     {
3304       priv->text_window->requisition.width = 0;
3305       priv->text_window->requisition.height = 0;
3306     }
3307   
3308   requisition->width = priv->text_window->requisition.width + focus_edge_width * 2;
3309   requisition->height = priv->text_window->requisition.height + focus_edge_width * 2;
3310
3311   if (priv->left_window)
3312     requisition->width += priv->left_window->requisition.width;
3313
3314   if (priv->right_window)
3315     requisition->width += priv->right_window->requisition.width;
3316
3317   if (priv->top_window)
3318     requisition->height += priv->top_window->requisition.height;
3319
3320   if (priv->bottom_window)
3321     requisition->height += priv->bottom_window->requisition.height;
3322
3323   border_width = gtk_container_get_border_width (GTK_CONTAINER (text_view));
3324   requisition->width += border_width * 2;
3325   requisition->height += border_width * 2;
3326   
3327   tmp_list = priv->children;
3328   while (tmp_list != NULL)
3329     {
3330       GtkTextViewChild *child = tmp_list->data;
3331
3332       if (child->anchor)
3333         {
3334           GtkRequisition child_req;
3335           GtkRequisition old_req;
3336
3337           gtk_widget_get_preferred_size (child->widget, &old_req, NULL);
3338
3339           gtk_widget_get_preferred_size (child->widget, &child_req, NULL);
3340
3341           /* Invalidate layout lines if required */
3342           if (priv->layout &&
3343               (old_req.width != child_req.width ||
3344                old_req.height != child_req.height))
3345             gtk_text_child_anchor_queue_resize (child->anchor,
3346                                                 priv->layout);
3347         }
3348       else
3349         {
3350           GtkRequisition child_req;
3351
3352           gtk_widget_get_preferred_size (child->widget,
3353                                          &child_req, NULL);
3354         }
3355
3356       tmp_list = g_slist_next (tmp_list);
3357     }
3358
3359   /* Cache the requested size of the text view so we can 
3360    * compare it in the changed_handler() */
3361   priv->cached_size_request = *requisition;
3362 }
3363
3364 static void
3365 gtk_text_view_get_preferred_width (GtkWidget *widget,
3366                                    gint      *minimum,
3367                                    gint      *natural)
3368 {
3369   GtkRequisition requisition;
3370
3371   gtk_text_view_size_request (widget, &requisition);
3372
3373   *minimum = *natural = requisition.width;
3374 }
3375
3376 static void
3377 gtk_text_view_get_preferred_height (GtkWidget *widget,
3378                                     gint      *minimum,
3379                                     gint      *natural)
3380 {
3381   GtkRequisition requisition;
3382
3383   gtk_text_view_size_request (widget, &requisition);
3384
3385   *minimum = *natural = requisition.height;
3386 }
3387
3388
3389 static void
3390 gtk_text_view_compute_child_allocation (GtkTextView      *text_view,
3391                                         GtkTextViewChild *vc,
3392                                         GtkAllocation    *allocation)
3393 {
3394   gint buffer_y;
3395   GtkTextIter iter;
3396   GtkRequisition req;
3397   
3398   gtk_text_buffer_get_iter_at_child_anchor (get_buffer (text_view),
3399                                             &iter,
3400                                             vc->anchor);
3401
3402   gtk_text_layout_get_line_yrange (text_view->priv->layout, &iter,
3403                                    &buffer_y, NULL);
3404
3405   buffer_y += vc->from_top_of_line;
3406
3407   allocation->x = vc->from_left_of_buffer - text_view->priv->xoffset;
3408   allocation->y = buffer_y - text_view->priv->yoffset;
3409
3410   gtk_widget_get_preferred_size (vc->widget, &req, NULL);
3411   allocation->width = req.width;
3412   allocation->height = req.height;
3413 }
3414
3415 static void
3416 gtk_text_view_update_child_allocation (GtkTextView      *text_view,
3417                                        GtkTextViewChild *vc)
3418 {
3419   GtkAllocation allocation;
3420
3421   gtk_text_view_compute_child_allocation (text_view, vc, &allocation);
3422   
3423   gtk_widget_size_allocate (vc->widget, &allocation);
3424
3425 #if 0
3426   g_print ("allocation for %p allocated to %d,%d yoffset = %d\n",
3427            vc->widget,
3428            vc->widget->allocation.x,
3429            vc->widget->allocation.y,
3430            text_view->priv->yoffset);
3431 #endif
3432 }
3433
3434 static void
3435 gtk_text_view_child_allocated (GtkTextLayout *layout,
3436                                GtkWidget     *child,
3437                                gint           x,
3438                                gint           y,
3439                                gpointer       data)
3440 {
3441   GtkTextViewChild *vc = NULL;
3442   GtkTextView *text_view = data;
3443   
3444   /* x,y is the position of the child from the top of the line, and
3445    * from the left of the buffer. We have to translate that into text
3446    * window coordinates, then size_allocate the child.
3447    */
3448
3449   vc = g_object_get_data (G_OBJECT (child),
3450                           "gtk-text-view-child");
3451
3452   g_assert (vc != NULL);
3453
3454   DV (g_print ("child allocated at %d,%d\n", x, y));
3455   
3456   vc->from_left_of_buffer = x;
3457   vc->from_top_of_line = y;
3458
3459   gtk_text_view_update_child_allocation (text_view, vc);
3460 }
3461
3462 static void
3463 gtk_text_view_allocate_children (GtkTextView *text_view)
3464 {
3465   GSList *tmp_list;
3466
3467   DV(g_print(G_STRLOC"\n"));
3468   
3469   tmp_list = text_view->priv->children;
3470   while (tmp_list != NULL)
3471     {
3472       GtkTextViewChild *child = tmp_list->data;
3473
3474       g_assert (child != NULL);
3475           
3476       if (child->anchor)
3477         {
3478           /* We need to force-validate the regions containing
3479            * children.
3480            */
3481           GtkTextIter child_loc;
3482           gtk_text_buffer_get_iter_at_child_anchor (get_buffer (text_view),
3483                                                     &child_loc,
3484                                                     child->anchor);
3485
3486           /* Since anchored children are only ever allocated from
3487            * gtk_text_layout_get_line_display() we have to make sure
3488            * that the display line caching in the layout doesn't 
3489            * get in the way. Invalidating the layout around the anchor
3490            * achieves this.
3491            */ 
3492           if (_gtk_widget_get_alloc_needed (child->widget))
3493             {
3494               GtkTextIter end = child_loc;
3495               gtk_text_iter_forward_char (&end);
3496               gtk_text_layout_invalidate (text_view->priv->layout, &child_loc, &end);
3497             }
3498
3499           gtk_text_layout_validate_yrange (text_view->priv->layout,
3500                                            &child_loc,
3501                                            0, 1);
3502         }
3503       else
3504         {
3505           GtkAllocation allocation;
3506           GtkRequisition child_req;
3507              
3508           allocation.x = child->x;
3509           allocation.y = child->y;
3510
3511           gtk_widget_get_preferred_size (child->widget, &child_req, NULL);
3512
3513           allocation.width = child_req.width;
3514           allocation.height = child_req.height;
3515           
3516           gtk_widget_size_allocate (child->widget, &allocation);          
3517         }
3518
3519       tmp_list = g_slist_next (tmp_list);
3520     }
3521 }
3522
3523 static void
3524 gtk_text_view_size_allocate (GtkWidget *widget,
3525                              GtkAllocation *allocation)
3526 {
3527   GtkAllocation widget_allocation;
3528   GtkTextView *text_view;
3529   GtkTextViewPrivate *priv;
3530   gint width, height;
3531   GdkRectangle text_rect;
3532   GdkRectangle left_rect;
3533   GdkRectangle right_rect;
3534   GdkRectangle top_rect;
3535   GdkRectangle bottom_rect;
3536   gint focus_edge_width;
3537   gint focus_width;
3538   guint border_width;
3539   gboolean interior_focus;
3540   gboolean size_changed;
3541   
3542   text_view = GTK_TEXT_VIEW (widget);
3543   priv = text_view->priv;
3544
3545   DV(g_print(G_STRLOC"\n"));
3546
3547   gtk_widget_get_allocation (widget, &widget_allocation);
3548   size_changed =
3549     widget_allocation.width != allocation->width ||
3550     widget_allocation.height != allocation->height;
3551
3552   border_width = gtk_container_get_border_width (GTK_CONTAINER (text_view));
3553
3554   gtk_widget_set_allocation (widget, allocation);
3555
3556   if (gtk_widget_get_realized (widget))
3557     {
3558       gdk_window_move_resize (gtk_widget_get_window (widget),
3559                               allocation->x, allocation->y,
3560                               allocation->width, allocation->height);
3561     }
3562
3563   /* distribute width/height among child windows. Ensure all
3564    * windows get at least a 1x1 allocation.
3565    */
3566
3567   gtk_widget_style_get (widget,
3568                         "interior-focus", &interior_focus,
3569                         "focus-line-width", &focus_width,
3570                         NULL);
3571
3572   if (interior_focus)
3573     focus_edge_width = 0;
3574   else
3575     focus_edge_width = focus_width;
3576   
3577   width = allocation->width - focus_edge_width * 2 - border_width * 2;
3578
3579   if (priv->left_window)
3580     left_rect.width = priv->left_window->requisition.width;
3581   else
3582     left_rect.width = 0;
3583
3584   width -= left_rect.width;
3585
3586   if (priv->right_window)
3587     right_rect.width = priv->right_window->requisition.width;
3588   else
3589     right_rect.width = 0;
3590
3591   width -= right_rect.width;
3592
3593   text_rect.width = MAX (1, width);
3594
3595   top_rect.width = text_rect.width;
3596   bottom_rect.width = text_rect.width;
3597
3598
3599   height = allocation->height - focus_edge_width * 2 - border_width * 2;
3600
3601   if (priv->top_window)
3602     top_rect.height = priv->top_window->requisition.height;
3603   else
3604     top_rect.height = 0;
3605
3606   height -= top_rect.height;
3607
3608   if (priv->bottom_window)
3609     bottom_rect.height = priv->bottom_window->requisition.height;
3610   else
3611     bottom_rect.height = 0;
3612
3613   height -= bottom_rect.height;
3614
3615   text_rect.height = MAX (1, height);
3616
3617   left_rect.height = text_rect.height;
3618   right_rect.height = text_rect.height;
3619
3620   /* Origins */
3621   left_rect.x = focus_edge_width + border_width;
3622   top_rect.y = focus_edge_width + border_width;
3623
3624   text_rect.x = left_rect.x + left_rect.width;
3625   text_rect.y = top_rect.y + top_rect.height;
3626
3627   left_rect.y = text_rect.y;
3628   right_rect.y = text_rect.y;
3629
3630   top_rect.x = text_rect.x;
3631   bottom_rect.x = text_rect.x;
3632
3633   right_rect.x = text_rect.x + text_rect.width;
3634   bottom_rect.y = text_rect.y + text_rect.height;
3635
3636   text_window_size_allocate (priv->text_window,
3637                              &text_rect);
3638
3639   if (priv->left_window)
3640     text_window_size_allocate (priv->left_window,
3641                                &left_rect);
3642
3643   if (priv->right_window)
3644     text_window_size_allocate (priv->right_window,
3645                                &right_rect);
3646
3647   if (priv->top_window)
3648     text_window_size_allocate (priv->top_window,
3649                                &top_rect);
3650
3651   if (priv->bottom_window)
3652     text_window_size_allocate (priv->bottom_window,
3653                                &bottom_rect);
3654
3655   gtk_text_view_update_layout_width (text_view);
3656   
3657   /* Note that this will do some layout validation */
3658   gtk_text_view_allocate_children (text_view);
3659
3660   /* Update adjustments */
3661   gtk_text_view_set_hadjustment_values (text_view);
3662   gtk_text_view_set_vadjustment_values (text_view);
3663
3664   /* The GTK resize loop processes all the pending exposes right
3665    * after doing the resize stuff, so the idle sizer won't have a
3666    * chance to run. So we do the work here. 
3667    */
3668   gtk_text_view_flush_first_validate (text_view);
3669
3670   /* widget->window doesn't get auto-redrawn as the layout is computed, so has to
3671    * be invalidated
3672    */
3673   if (size_changed && gtk_widget_get_realized (widget))
3674     gdk_window_invalidate_rect (gtk_widget_get_window (widget), NULL, FALSE);
3675 }
3676
3677 static void
3678 gtk_text_view_get_first_para_iter (GtkTextView *text_view,
3679                                    GtkTextIter *iter)
3680 {
3681   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), iter,
3682                                     text_view->priv->first_para_mark);
3683 }
3684
3685 static void
3686 gtk_text_view_validate_onscreen (GtkTextView *text_view)
3687 {
3688   GtkWidget *widget;
3689   GtkTextViewPrivate *priv;
3690
3691   widget = GTK_WIDGET (text_view);
3692   priv = text_view->priv;
3693   
3694   DV(g_print(">Validating onscreen ("G_STRLOC")\n"));
3695   
3696   if (SCREEN_HEIGHT (widget) > 0)
3697     {
3698       GtkTextIter first_para;
3699
3700       /* Be sure we've validated the stuff onscreen; if we
3701        * scrolled, these calls won't have any effect, because
3702        * they were called in the recursive validate_onscreen
3703        */
3704       gtk_text_view_get_first_para_iter (text_view, &first_para);
3705
3706       gtk_text_layout_validate_yrange (priv->layout,
3707                                        &first_para,
3708                                        0,
3709                                        priv->first_para_pixels +
3710                                        SCREEN_HEIGHT (widget));
3711     }
3712
3713   priv->onscreen_validated = TRUE;
3714
3715   DV(g_print(">Done validating onscreen, onscreen_validated = TRUE ("G_STRLOC")\n"));
3716   
3717   /* This can have the odd side effect of triggering a scroll, which should
3718    * flip "onscreen_validated" back to FALSE, but should also get us
3719    * back into this function to turn it on again.
3720    */
3721   gtk_text_view_update_adjustments (text_view);
3722
3723   g_assert (priv->onscreen_validated);
3724 }
3725
3726 static void
3727 gtk_text_view_flush_first_validate (GtkTextView *text_view)
3728 {
3729   GtkTextViewPrivate *priv = text_view->priv;
3730
3731   if (priv->first_validate_idle == 0)
3732     return;
3733
3734   /* Do this first, which means that if an "invalidate"
3735    * occurs during any of this process, a new first_validate_callback
3736    * will be installed, and we'll start again.
3737    */
3738   DV (g_print ("removing first validate in %s\n", G_STRLOC));
3739   g_source_remove (priv->first_validate_idle);
3740   priv->first_validate_idle = 0;
3741   
3742   /* be sure we have up-to-date screen size set on the
3743    * layout.
3744    */
3745   gtk_text_view_update_layout_width (text_view);
3746
3747   /* Bail out if we invalidated stuff; scrolling right away will just
3748    * confuse the issue.
3749    */
3750   if (priv->first_validate_idle != 0)
3751     {
3752       DV(g_print(">Width change forced requeue ("G_STRLOC")\n"));
3753     }
3754   else
3755     {
3756       /* scroll to any marks, if that's pending. This can jump us to
3757        * the validation codepath used for scrolling onscreen, if so we
3758        * bail out.  It won't jump if already in that codepath since
3759        * value_changed is not recursive, so also validate if
3760        * necessary.
3761        */
3762       if (!gtk_text_view_flush_scroll (text_view) ||
3763           !priv->onscreen_validated)
3764         gtk_text_view_validate_onscreen (text_view);
3765       
3766       DV(g_print(">Leaving first validate idle ("G_STRLOC")\n"));
3767       
3768       g_assert (priv->onscreen_validated);
3769     }
3770 }
3771
3772 static gboolean
3773 first_validate_callback (gpointer data)
3774 {
3775   GtkTextView *text_view = data;
3776
3777   /* Note that some of this code is duplicated at the end of size_allocate,
3778    * keep in sync with that.
3779    */
3780   
3781   DV(g_print(G_STRLOC"\n"));
3782
3783   gtk_text_view_flush_first_validate (text_view);
3784   
3785   return FALSE;
3786 }
3787
3788 static gboolean
3789 incremental_validate_callback (gpointer data)
3790 {
3791   GtkTextView *text_view = data;
3792   gboolean result = TRUE;
3793
3794   DV(g_print(G_STRLOC"\n"));
3795   
3796   gtk_text_layout_validate (text_view->priv->layout, 2000);
3797
3798   gtk_text_view_update_adjustments (text_view);
3799   
3800   if (gtk_text_layout_is_valid (text_view->priv->layout))
3801     {
3802       text_view->priv->incremental_validate_idle = 0;
3803       result = FALSE;
3804     }
3805
3806   return result;
3807 }
3808
3809 static void
3810 gtk_text_view_invalidate (GtkTextView *text_view)
3811 {
3812   GtkTextViewPrivate *priv = text_view->priv;
3813
3814   DV (g_print (">Invalidate, onscreen_validated = %d now FALSE ("G_STRLOC")\n",
3815                priv->onscreen_validated));
3816
3817   priv->onscreen_validated = FALSE;
3818
3819   /* We'll invalidate when the layout is created */
3820   if (priv->layout == NULL)
3821     return;
3822   
3823   if (!priv->first_validate_idle)
3824     {
3825       priv->first_validate_idle = gdk_threads_add_idle_full (GTK_PRIORITY_RESIZE - 2, first_validate_callback, text_view, NULL);
3826       DV (g_print (G_STRLOC": adding first validate idle %d\n",
3827                    priv->first_validate_idle));
3828     }
3829       
3830   if (!priv->incremental_validate_idle)
3831     {
3832       priv->incremental_validate_idle = gdk_threads_add_idle_full (GTK_TEXT_VIEW_PRIORITY_VALIDATE, incremental_validate_callback, text_view, NULL);
3833       DV (g_print (G_STRLOC": adding incremental validate idle %d\n",
3834                    priv->incremental_validate_idle));
3835     }
3836 }
3837
3838 static void
3839 invalidated_handler (GtkTextLayout *layout,
3840                      gpointer       data)
3841 {
3842   GtkTextView *text_view;
3843
3844   text_view = GTK_TEXT_VIEW (data);
3845
3846   DV (g_print ("Invalidating due to layout invalidate signal\n"));
3847   gtk_text_view_invalidate (text_view);
3848 }
3849
3850 static void
3851 changed_handler (GtkTextLayout     *layout,
3852                  gint               start_y,
3853                  gint               old_height,
3854                  gint               new_height,
3855                  gpointer           data)
3856 {
3857   GtkTextView *text_view;
3858   GtkTextViewPrivate *priv;
3859   GtkWidget *widget;
3860   GdkRectangle visible_rect;
3861   GdkRectangle redraw_rect;
3862   
3863   text_view = GTK_TEXT_VIEW (data);
3864   priv = text_view->priv;
3865   widget = GTK_WIDGET (data);
3866   
3867   DV(g_print(">Lines Validated ("G_STRLOC")\n"));
3868
3869   if (gtk_widget_get_realized (widget))
3870     {      
3871       gtk_text_view_get_visible_rect (text_view, &visible_rect);
3872
3873       redraw_rect.x = visible_rect.x;
3874       redraw_rect.width = visible_rect.width;
3875       redraw_rect.y = start_y;
3876
3877       if (old_height == new_height)
3878         redraw_rect.height = old_height;
3879       else if (start_y + old_height > visible_rect.y)
3880         redraw_rect.height = MAX (0, visible_rect.y + visible_rect.height - start_y);
3881       else
3882         redraw_rect.height = 0;
3883         
3884       if (gdk_rectangle_intersect (&redraw_rect, &visible_rect, &redraw_rect))
3885         {
3886           /* text_window_invalidate_rect() takes buffer coordinates */
3887           text_window_invalidate_rect (priv->text_window,
3888                                        &redraw_rect);
3889
3890           DV(g_print(" invalidated rect: %d,%d %d x %d\n",
3891                      redraw_rect.x,
3892                      redraw_rect.y,
3893                      redraw_rect.width,
3894                      redraw_rect.height));
3895           
3896           if (priv->left_window)
3897             text_window_invalidate_rect (priv->left_window,
3898                                          &redraw_rect);
3899           if (priv->right_window)
3900             text_window_invalidate_rect (priv->right_window,
3901                                          &redraw_rect);
3902           if (priv->top_window)
3903             text_window_invalidate_rect (priv->top_window,
3904                                          &redraw_rect);
3905           if (priv->bottom_window)
3906             text_window_invalidate_rect (priv->bottom_window,
3907                                          &redraw_rect);
3908
3909           queue_update_im_spot_location (text_view);
3910         }
3911     }
3912   
3913   if (old_height != new_height)
3914     {
3915       GSList *tmp_list;
3916       int new_first_para_top;
3917       int old_first_para_top;
3918       GtkTextIter first;
3919       
3920       /* If the bottom of the old area was above the top of the
3921        * screen, we need to scroll to keep the current top of the
3922        * screen in place.  Remember that first_para_pixels is the
3923        * position of the top of the screen in coordinates relative to
3924        * the first paragraph onscreen.
3925        *
3926        * In short we are adding the height delta of the portion of the
3927        * changed region above first_para_mark to priv->yoffset.
3928        */
3929       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &first,
3930                                         priv->first_para_mark);
3931
3932       gtk_text_layout_get_line_yrange (layout, &first, &new_first_para_top, NULL);
3933
3934       old_first_para_top = priv->yoffset - priv->first_para_pixels;
3935
3936       if (new_first_para_top != old_first_para_top)
3937         {
3938           priv->yoffset += new_first_para_top - old_first_para_top;
3939           
3940           gtk_adjustment_set_value (text_view->priv->vadjustment, priv->yoffset);
3941         }
3942
3943       /* FIXME be smarter about which anchored widgets we update */
3944
3945       tmp_list = priv->children;
3946       while (tmp_list != NULL)
3947         {
3948           GtkTextViewChild *child = tmp_list->data;
3949
3950           if (child->anchor)
3951             gtk_text_view_update_child_allocation (text_view, child);
3952
3953           tmp_list = g_slist_next (tmp_list);
3954         }
3955     }
3956
3957   {
3958     GtkRequisition old_req = priv->cached_size_request;
3959     GtkRequisition new_req;
3960
3961     /* Use this instead of gtk_widget_size_request wrapper
3962      * to avoid the optimization which just returns widget->requisition
3963      * if a resize hasn't been queued.
3964      */
3965     gtk_text_view_size_request (widget, &new_req);
3966
3967     if (old_req.width != new_req.width ||
3968         old_req.height != new_req.height)
3969       {
3970         gtk_widget_queue_resize_no_redraw (widget);
3971       }
3972   }
3973 }
3974
3975 static void
3976 gtk_text_view_realize (GtkWidget *widget)
3977 {
3978   GtkAllocation allocation;
3979   GtkTextView *text_view;
3980   GtkTextViewPrivate *priv;
3981   GtkStyleContext *context;
3982   GtkStateFlags state;
3983   GdkWindow *window;
3984   GdkWindowAttr attributes;
3985   gint attributes_mask;
3986   GSList *tmp_list;
3987   GdkRGBA color;
3988
3989   text_view = GTK_TEXT_VIEW (widget);
3990   priv = text_view->priv;
3991
3992   gtk_widget_set_realized (widget, TRUE);
3993
3994   gtk_widget_get_allocation (widget, &allocation);
3995
3996   attributes.window_type = GDK_WINDOW_CHILD;
3997   attributes.x = allocation.x;
3998   attributes.y = allocation.y;
3999   attributes.width = allocation.width;
4000   attributes.height = allocation.height;
4001   attributes.wclass = GDK_INPUT_OUTPUT;
4002   attributes.visual = gtk_widget_get_visual (widget);
4003   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK | GDK_EXPOSURE_MASK;
4004
4005   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
4006
4007   window = gdk_window_new (gtk_widget_get_parent_window (widget),
4008                            &attributes, attributes_mask);
4009   gtk_widget_set_window (widget, window);
4010   gdk_window_set_user_data (window, widget);
4011
4012   context = gtk_widget_get_style_context (widget);
4013   state = gtk_widget_get_state_flags (widget);
4014
4015   gtk_style_context_get_background_color (context, state, &color);
4016   gdk_window_set_background_rgba (window, &color);
4017
4018   text_window_realize (priv->text_window, widget);
4019
4020   if (priv->left_window)
4021     text_window_realize (priv->left_window, widget);
4022
4023   if (priv->top_window)
4024     text_window_realize (priv->top_window, widget);
4025
4026   if (priv->right_window)
4027     text_window_realize (priv->right_window, widget);
4028
4029   if (priv->bottom_window)
4030     text_window_realize (priv->bottom_window, widget);
4031
4032   gtk_text_view_ensure_layout (text_view);
4033   gtk_text_view_invalidate (text_view);
4034
4035   if (priv->buffer)
4036     {
4037       GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4038                                                           GDK_SELECTION_PRIMARY);
4039       gtk_text_buffer_add_selection_clipboard (priv->buffer, clipboard);
4040     }
4041
4042   tmp_list = priv->children;
4043   while (tmp_list != NULL)
4044     {
4045       GtkTextViewChild *vc = tmp_list->data;
4046       
4047       text_view_child_set_parent_window (text_view, vc);
4048       
4049       tmp_list = tmp_list->next;
4050     }
4051
4052   /* Ensure updating the spot location. */
4053   gtk_text_view_update_im_spot_location (text_view);
4054 }
4055
4056 static void
4057 gtk_text_view_unrealize (GtkWidget *widget)
4058 {
4059   GtkTextView *text_view;
4060   GtkTextViewPrivate *priv;
4061
4062   text_view = GTK_TEXT_VIEW (widget);
4063   priv = text_view->priv;
4064
4065   if (priv->buffer)
4066     {
4067       GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4068                                                           GDK_SELECTION_PRIMARY);
4069       gtk_text_buffer_remove_selection_clipboard (priv->buffer, clipboard);
4070     }
4071
4072   gtk_text_view_remove_validate_idles (text_view);
4073
4074   if (priv->popup_menu)
4075     {
4076       gtk_widget_destroy (priv->popup_menu);
4077       priv->popup_menu = NULL;
4078     }
4079
4080   text_window_unrealize (priv->text_window);
4081
4082   if (priv->left_window)
4083     text_window_unrealize (priv->left_window);
4084
4085   if (priv->top_window)
4086     text_window_unrealize (priv->top_window);
4087
4088   if (priv->right_window)
4089     text_window_unrealize (priv->right_window);
4090
4091   if (priv->bottom_window)
4092     text_window_unrealize (priv->bottom_window);
4093
4094   GTK_WIDGET_CLASS (gtk_text_view_parent_class)->unrealize (widget);
4095 }
4096
4097 static void
4098 gtk_text_view_set_background (GtkTextView *text_view)
4099 {
4100   GtkStyleContext *context;
4101   GtkStateFlags state;
4102   GtkWidget *widget;
4103   GtkTextViewPrivate *priv;
4104   GdkRGBA color;
4105
4106   widget = GTK_WIDGET (text_view);
4107   priv = text_view->priv;
4108
4109   context = gtk_widget_get_style_context (widget);
4110   state = gtk_widget_get_state_flags (widget);
4111
4112   /* Set bin window background */
4113   gtk_style_context_save (context);
4114   gtk_style_context_add_class (context, GTK_STYLE_CLASS_VIEW);
4115
4116   gtk_style_context_get_background_color (context, state, &color);
4117   gdk_window_set_background_rgba (priv->text_window->bin_window, &color);
4118
4119   gtk_style_context_restore (context);
4120
4121   /* Set lateral panes background */
4122   gtk_style_context_get_background_color (context, state, &color);
4123
4124   gdk_window_set_background_rgba (gtk_widget_get_window (widget), &color);
4125
4126   if (priv->left_window)
4127     gdk_window_set_background_rgba (priv->left_window->bin_window, &color);
4128
4129   if (priv->right_window)
4130     gdk_window_set_background_rgba (priv->right_window->bin_window, &color);
4131
4132   if (priv->top_window)
4133     gdk_window_set_background_rgba (priv->top_window->bin_window, &color);
4134
4135   if (priv->bottom_window)
4136     gdk_window_set_background_rgba (priv->bottom_window->bin_window, &color);
4137 }
4138
4139 static void
4140 gtk_text_view_style_updated (GtkWidget *widget)
4141 {
4142   GtkTextView *text_view;
4143   GtkTextViewPrivate *priv;
4144   PangoContext *ltr_context, *rtl_context;
4145
4146   text_view = GTK_TEXT_VIEW (widget);
4147   priv = text_view->priv;
4148
4149   GTK_WIDGET_CLASS (gtk_text_view_parent_class)->style_updated (widget);
4150
4151   if (gtk_widget_get_realized (widget))
4152     {
4153       gtk_text_view_set_background (text_view);
4154     }
4155
4156   if (priv->layout && priv->layout->default_style)
4157     {
4158       gtk_text_view_set_attributes_from_style (text_view,
4159                                                priv->layout->default_style);
4160
4161       ltr_context = gtk_widget_create_pango_context (widget);
4162       pango_context_set_base_dir (ltr_context, PANGO_DIRECTION_LTR);
4163       rtl_context = gtk_widget_create_pango_context (widget);
4164       pango_context_set_base_dir (rtl_context, PANGO_DIRECTION_RTL);
4165
4166       gtk_text_layout_set_contexts (priv->layout, ltr_context, rtl_context);
4167
4168       g_object_unref (ltr_context);
4169       g_object_unref (rtl_context);
4170     }
4171 }
4172
4173 static void
4174 gtk_text_view_direction_changed (GtkWidget        *widget,
4175                                  GtkTextDirection  previous_direction)
4176 {
4177   GtkTextViewPrivate *priv = GTK_TEXT_VIEW (widget)->priv;
4178
4179   if (priv->layout && priv->layout->default_style)
4180     {
4181       priv->layout->default_style->direction = gtk_widget_get_direction (widget);
4182
4183       gtk_text_layout_default_style_changed (priv->layout);
4184     }
4185 }
4186
4187 static void
4188 gtk_text_view_state_flags_changed (GtkWidget     *widget,
4189                                    GtkStateFlags  previous_state)
4190 {
4191   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4192   GdkCursor *cursor;
4193
4194   if (gtk_widget_get_realized (widget))
4195     {
4196       gtk_text_view_set_background (text_view);
4197
4198       if (gtk_widget_is_sensitive (widget))
4199         cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget), GDK_XTERM);
4200       else
4201         cursor = NULL;
4202
4203       gdk_window_set_cursor (text_view->priv->text_window->bin_window, cursor);
4204
4205       if (cursor)
4206       g_object_unref (cursor);
4207
4208       text_view->priv->mouse_cursor_obscured = FALSE;
4209     }
4210
4211   if (!gtk_widget_is_sensitive (widget))
4212     {
4213       /* Clear any selection */
4214       gtk_text_view_unselect (text_view);
4215     }
4216   
4217   gtk_widget_queue_draw (widget);
4218 }
4219
4220 static void
4221 set_invisible_cursor (GdkWindow *window)
4222 {
4223   GdkDisplay *display;
4224   GdkCursor *cursor;
4225
4226   display = gdk_window_get_display (window);
4227   cursor = gdk_cursor_new_for_display (display, GDK_BLANK_CURSOR);
4228  
4229   gdk_window_set_cursor (window, cursor);
4230   
4231   g_object_unref (cursor);
4232 }
4233
4234 static void
4235 gtk_text_view_obscure_mouse_cursor (GtkTextView *text_view)
4236 {
4237   if (text_view->priv->mouse_cursor_obscured)
4238     return;
4239
4240   set_invisible_cursor (text_view->priv->text_window->bin_window);
4241   
4242   text_view->priv->mouse_cursor_obscured = TRUE;
4243 }
4244
4245 static void
4246 gtk_text_view_unobscure_mouse_cursor (GtkTextView *text_view)
4247 {
4248   if (text_view->priv->mouse_cursor_obscured)
4249     {
4250       GdkCursor *cursor;
4251       
4252       cursor = gdk_cursor_new_for_display (gtk_widget_get_display (GTK_WIDGET (text_view)),
4253                                            GDK_XTERM);
4254       gdk_window_set_cursor (text_view->priv->text_window->bin_window, cursor);
4255       g_object_unref (cursor);
4256       text_view->priv->mouse_cursor_obscured = FALSE;
4257     }
4258 }
4259
4260 static void
4261 gtk_text_view_grab_notify (GtkWidget *widget,
4262                            gboolean   was_grabbed)
4263 {
4264   GtkTextViewPrivate *priv;
4265
4266   priv = GTK_TEXT_VIEW (widget)->priv;
4267
4268   if (priv->grab_device &&
4269       gtk_widget_device_is_shadowed (widget, priv->grab_device))
4270     {
4271       gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget));
4272       gtk_text_view_unobscure_mouse_cursor (GTK_TEXT_VIEW (widget));
4273     }
4274 }
4275
4276
4277 /*
4278  * Events
4279  */
4280
4281 static gboolean
4282 get_event_coordinates (GdkEvent *event, gint *x, gint *y)
4283 {
4284   if (event)
4285     switch (event->type)
4286       {
4287       case GDK_MOTION_NOTIFY:
4288         *x = event->motion.x;
4289         *y = event->motion.y;
4290         return TRUE;
4291         break;
4292
4293       case GDK_BUTTON_PRESS:
4294       case GDK_2BUTTON_PRESS:
4295       case GDK_3BUTTON_PRESS:
4296       case GDK_BUTTON_RELEASE:
4297         *x = event->button.x;
4298         *y = event->button.y;
4299         return TRUE;
4300         break;
4301
4302       case GDK_KEY_PRESS:
4303       case GDK_KEY_RELEASE:
4304       case GDK_ENTER_NOTIFY:
4305       case GDK_LEAVE_NOTIFY:
4306       case GDK_PROPERTY_NOTIFY:
4307       case GDK_SELECTION_CLEAR:
4308       case GDK_SELECTION_REQUEST:
4309       case GDK_SELECTION_NOTIFY:
4310       case GDK_PROXIMITY_IN:
4311       case GDK_PROXIMITY_OUT:
4312       case GDK_DRAG_ENTER:
4313       case GDK_DRAG_LEAVE:
4314       case GDK_DRAG_MOTION:
4315       case GDK_DRAG_STATUS:
4316       case GDK_DROP_START:
4317       case GDK_DROP_FINISHED:
4318       default:
4319         return FALSE;
4320         break;
4321       }
4322
4323   return FALSE;
4324 }
4325
4326 static gint
4327 emit_event_on_tags (GtkWidget   *widget,
4328                     GdkEvent    *event,
4329                     GtkTextIter *iter)
4330 {
4331   GSList *tags;
4332   GSList *tmp;
4333   gboolean retval = FALSE;
4334
4335   tags = gtk_text_iter_get_tags (iter);
4336
4337   tmp = tags;
4338   while (tmp != NULL)
4339     {
4340       GtkTextTag *tag = tmp->data;
4341
4342       if (gtk_text_tag_event (tag, G_OBJECT (widget), event, iter))
4343         {
4344           retval = TRUE;
4345           break;
4346         }
4347
4348       tmp = g_slist_next (tmp);
4349     }
4350
4351   g_slist_free (tags);
4352
4353   return retval;
4354 }
4355
4356 static gint
4357 gtk_text_view_event (GtkWidget *widget, GdkEvent *event)
4358 {
4359   GtkTextView *text_view;
4360   GtkTextViewPrivate *priv;
4361   gint x = 0, y = 0;
4362
4363   text_view = GTK_TEXT_VIEW (widget);
4364   priv = text_view->priv;
4365
4366   if (priv->layout == NULL ||
4367       get_buffer (text_view) == NULL)
4368     return FALSE;
4369
4370   if (event->any.window != priv->text_window->bin_window)
4371     return FALSE;
4372
4373   if (get_event_coordinates (event, &x, &y))
4374     {
4375       GtkTextIter iter;
4376
4377       x += priv->xoffset;
4378       y += priv->yoffset;
4379
4380       /* FIXME this is slow and we do it twice per event.
4381        * My favorite solution is to have GtkTextLayout cache
4382        * the last couple lookups.
4383        */
4384       gtk_text_layout_get_iter_at_pixel (priv->layout,
4385                                          &iter,
4386                                          x, y);
4387
4388       return emit_event_on_tags (widget, event, &iter);
4389     }
4390   else if (event->type == GDK_KEY_PRESS ||
4391            event->type == GDK_KEY_RELEASE)
4392     {
4393       GtkTextIter iter;
4394
4395       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter,
4396                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
4397
4398       return emit_event_on_tags (widget, event, &iter);
4399     }
4400   else
4401     return FALSE;
4402 }
4403
4404 static gint
4405 gtk_text_view_key_press_event (GtkWidget *widget, GdkEventKey *event)
4406 {
4407   GtkTextView *text_view;
4408   GtkTextViewPrivate *priv;
4409   GtkTextMark *insert;
4410   GtkTextIter iter;
4411   gboolean can_insert;
4412   gboolean retval = FALSE;
4413   gboolean obscure = FALSE;
4414
4415   text_view = GTK_TEXT_VIEW (widget);
4416   priv = text_view->priv;
4417   
4418   if (priv->layout == NULL ||
4419       get_buffer (text_view) == NULL)
4420     return FALSE;
4421
4422   /* Make sure input method knows where it is */
4423   flush_update_im_spot_location (text_view);
4424
4425   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4426   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4427   can_insert = gtk_text_iter_can_insert (&iter, priv->editable);
4428   if (gtk_im_context_filter_keypress (priv->im_context, event))
4429     {
4430       priv->need_im_reset = TRUE;
4431       if (!can_insert)
4432         gtk_text_view_reset_im_context (text_view);
4433       obscure = can_insert;
4434       retval = TRUE;
4435     }
4436   /* Binding set */
4437   else if (GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_press_event (widget, event))
4438     {
4439       retval = TRUE;
4440     }
4441   /* use overall editability not can_insert, more predictable for users */
4442   else if (priv->editable &&
4443            (event->keyval == GDK_KEY_Return ||
4444             event->keyval == GDK_KEY_ISO_Enter ||
4445             event->keyval == GDK_KEY_KP_Enter))
4446     {
4447       /* this won't actually insert the newline if the cursor isn't
4448        * editable
4449        */
4450       gtk_text_view_reset_im_context (text_view);
4451       gtk_text_view_commit_text (text_view, "\n");
4452
4453       obscure = TRUE;
4454       retval = TRUE;
4455     }
4456   /* Pass through Tab as literal tab, unless Control is held down */
4457   else if ((event->keyval == GDK_KEY_Tab ||
4458             event->keyval == GDK_KEY_KP_Tab ||
4459             event->keyval == GDK_KEY_ISO_Left_Tab) &&
4460            !(event->state & GDK_CONTROL_MASK))
4461     {
4462       /* If the text widget isn't editable overall, or if the application
4463        * has turned off "accepts_tab", move the focus instead
4464        */
4465       if (priv->accepts_tab && priv->editable)
4466         {
4467           gtk_text_view_reset_im_context (text_view);
4468           gtk_text_view_commit_text (text_view, "\t");
4469           obscure = TRUE;
4470         }
4471       else
4472         g_signal_emit_by_name (text_view, "move-focus",
4473                                (event->state & GDK_SHIFT_MASK) ?
4474                                GTK_DIR_TAB_BACKWARD : GTK_DIR_TAB_FORWARD);
4475
4476       retval = TRUE;
4477     }
4478   else
4479     retval = FALSE;
4480
4481   if (obscure)
4482     gtk_text_view_obscure_mouse_cursor (text_view);
4483   
4484   gtk_text_view_reset_blink_time (text_view);
4485   gtk_text_view_pend_cursor_blink (text_view);
4486
4487   return retval;
4488 }
4489
4490 static gint
4491 gtk_text_view_key_release_event (GtkWidget *widget, GdkEventKey *event)
4492 {
4493   GtkTextView *text_view;
4494   GtkTextViewPrivate *priv;
4495   GtkTextMark *insert;
4496   GtkTextIter iter;
4497
4498   text_view = GTK_TEXT_VIEW (widget);
4499   priv = text_view->priv;
4500
4501   if (priv->layout == NULL || get_buffer (text_view) == NULL)
4502     return FALSE;
4503       
4504   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4505   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4506   if (gtk_text_iter_can_insert (&iter, priv->editable) &&
4507       gtk_im_context_filter_keypress (priv->im_context, event))
4508     {
4509       priv->need_im_reset = TRUE;
4510       return TRUE;
4511     }
4512   else
4513     return GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_release_event (widget, event);
4514 }
4515
4516 static gint
4517 gtk_text_view_button_press_event (GtkWidget *widget, GdkEventButton *event)
4518 {
4519   GtkTextView *text_view;
4520   GtkTextViewPrivate *priv;
4521
4522   text_view = GTK_TEXT_VIEW (widget);
4523   priv = text_view->priv;
4524
4525   gtk_widget_grab_focus (widget);
4526
4527   if (event->window != priv->text_window->bin_window)
4528     {
4529       /* Remove selection if any. */
4530       gtk_text_view_unselect (text_view);
4531       return FALSE;
4532     }
4533
4534   gtk_text_view_reset_blink_time (text_view);
4535
4536 #if 0
4537   /* debug hack */
4538   if (event->button == 3 && (event->state & GDK_CONTROL_MASK) != 0)
4539     _gtk_text_buffer_spew (GTK_TEXT_VIEW (widget)->buffer);
4540   else if (event->button == 3)
4541     gtk_text_layout_spew (GTK_TEXT_VIEW (widget)->layout);
4542 #endif
4543
4544   if (event->type == GDK_BUTTON_PRESS)
4545     {
4546       gtk_text_view_reset_im_context (text_view);
4547
4548       if (gdk_event_triggers_context_menu ((GdkEvent *) event))
4549         {
4550           gtk_text_view_do_popup (text_view, event);
4551           return TRUE;
4552         }
4553       else if (event->button == 1)
4554         {
4555           /* If we're in the selection, start a drag copy/move of the
4556            * selection; otherwise, start creating a new selection.
4557            */
4558           GtkTextIter iter;
4559           GtkTextIter start, end;
4560
4561           gtk_text_layout_get_iter_at_pixel (priv->layout,
4562                                              &iter,
4563                                              event->x + priv->xoffset,
4564                                              event->y + priv->yoffset);
4565
4566           if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
4567                                                     &start, &end) &&
4568               gtk_text_iter_in_range (&iter, &start, &end) &&
4569               !(event->state &
4570                 gtk_widget_get_modifier_mask (widget,
4571                                               GDK_MODIFIER_INTENT_EXTEND_SELECTION)))
4572             {
4573               priv->drag_start_x = event->x;
4574               priv->drag_start_y = event->y;
4575               priv->pending_place_cursor_button = event->button;
4576             }
4577           else
4578             {
4579               gtk_text_view_start_selection_drag (text_view, &iter, event);
4580             }
4581
4582           return TRUE;
4583         }
4584       else if (event->button == 2)
4585         {
4586           GtkTextIter iter;
4587
4588           /* We do not want to scroll back to the insert iter when we paste
4589              with the middle button */
4590           priv->scroll_after_paste = FALSE;
4591
4592           gtk_text_layout_get_iter_at_pixel (priv->layout,
4593                                              &iter,
4594                                              event->x + priv->xoffset,
4595                                              event->y + priv->yoffset);
4596
4597           gtk_text_buffer_paste_clipboard (get_buffer (text_view),
4598                                            gtk_widget_get_clipboard (widget, GDK_SELECTION_PRIMARY),
4599                                            &iter,
4600                                            priv->editable);
4601           return TRUE;
4602         }
4603     }
4604   else if ((event->type == GDK_2BUTTON_PRESS ||
4605             event->type == GDK_3BUTTON_PRESS) &&
4606            event->button == 1) 
4607     {
4608       GtkTextIter iter;
4609
4610       gtk_text_view_end_selection_drag (text_view);
4611
4612       gtk_text_layout_get_iter_at_pixel (priv->layout,
4613                                          &iter,
4614                                          event->x + priv->xoffset,
4615                                          event->y + priv->yoffset);
4616       
4617       gtk_text_view_start_selection_drag (text_view, &iter, event);
4618       return TRUE;
4619     }
4620   
4621   return FALSE;
4622 }
4623
4624 static gint
4625 gtk_text_view_button_release_event (GtkWidget *widget, GdkEventButton *event)
4626 {
4627   GtkTextView *text_view;
4628   GtkTextViewPrivate *priv;
4629
4630   text_view = GTK_TEXT_VIEW (widget);
4631   priv = text_view->priv;
4632
4633   if (event->window != priv->text_window->bin_window)
4634     return FALSE;
4635
4636   if (event->button == 1)
4637     {
4638       if (priv->drag_start_x >= 0)
4639         {
4640           priv->drag_start_x = -1;
4641           priv->drag_start_y = -1;
4642         }
4643
4644       if (gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget)))
4645         return TRUE;
4646       else if (priv->pending_place_cursor_button == event->button)
4647         {
4648           GtkTextIter iter;
4649
4650           /* Unselect everything; we clicked inside selection, but
4651            * didn't move by the drag threshold, so just clear selection
4652            * and place cursor.
4653            */
4654           gtk_text_layout_get_iter_at_pixel (priv->layout,
4655                                              &iter,
4656                                              event->x + priv->xoffset,
4657                                              event->y + priv->yoffset);
4658
4659           gtk_text_buffer_place_cursor (get_buffer (text_view), &iter);
4660           gtk_text_view_check_cursor_blink (text_view);
4661           
4662           priv->pending_place_cursor_button = 0;
4663           
4664           return FALSE;
4665         }
4666     }
4667
4668   return FALSE;
4669 }
4670
4671 static void
4672 keymap_direction_changed (GdkKeymap   *keymap,
4673                           GtkTextView *text_view)
4674 {
4675   gtk_text_view_check_keymap_direction (text_view);
4676 }
4677
4678 static gint
4679 gtk_text_view_focus_in_event (GtkWidget *widget, GdkEventFocus *event)
4680 {
4681   GtkTextView *text_view;
4682   GtkTextViewPrivate *priv;
4683
4684   text_view = GTK_TEXT_VIEW (widget);
4685   priv = text_view->priv;
4686
4687   gtk_widget_queue_draw (widget);
4688
4689   DV(g_print (G_STRLOC": focus_in_event\n"));
4690
4691   gtk_text_view_reset_blink_time (text_view);
4692
4693   if (priv->cursor_visible && priv->layout)
4694     {
4695       gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
4696       gtk_text_view_check_cursor_blink (text_view);
4697     }
4698
4699   g_signal_connect (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
4700                     "direction-changed",
4701                     G_CALLBACK (keymap_direction_changed), text_view);
4702   gtk_text_view_check_keymap_direction (text_view);
4703
4704   if (priv->editable)
4705     {
4706       priv->need_im_reset = TRUE;
4707       gtk_im_context_focus_in (priv->im_context);
4708     }
4709
4710   return FALSE;
4711 }
4712
4713 static gint
4714 gtk_text_view_focus_out_event (GtkWidget *widget, GdkEventFocus *event)
4715 {
4716   GtkTextView *text_view;
4717   GtkTextViewPrivate *priv;
4718
4719   text_view = GTK_TEXT_VIEW (widget);
4720   priv = text_view->priv;
4721
4722   gtk_text_view_end_selection_drag (text_view);
4723
4724   gtk_widget_queue_draw (widget);
4725
4726   DV(g_print (G_STRLOC": focus_out_event\n"));
4727   
4728   if (priv->cursor_visible && priv->layout)
4729     {
4730       gtk_text_view_check_cursor_blink (text_view);
4731       gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
4732     }
4733
4734   g_signal_handlers_disconnect_by_func (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
4735                                         keymap_direction_changed,
4736                                         text_view);
4737
4738   if (priv->editable)
4739     {
4740       priv->need_im_reset = TRUE;
4741       gtk_im_context_focus_out (priv->im_context);
4742     }
4743
4744   return FALSE;
4745 }
4746
4747 static gint
4748 gtk_text_view_motion_event (GtkWidget *widget, GdkEventMotion *event)
4749 {
4750   GtkTextView *text_view;
4751   GtkTextViewPrivate *priv;
4752
4753   text_view = GTK_TEXT_VIEW (widget);
4754   priv = text_view->priv;
4755
4756   gtk_text_view_unobscure_mouse_cursor (text_view);
4757
4758   if (event->window == priv->text_window->bin_window &&
4759       priv->drag_start_x >= 0)
4760     {
4761       gint x = event->x;
4762       gint y = event->y;
4763
4764       gdk_event_request_motions (event);
4765
4766       if (gtk_drag_check_threshold (widget,
4767                                     priv->drag_start_x, 
4768                                     priv->drag_start_y,
4769                                     x, y))
4770         {
4771           GtkTextIter iter;
4772           gint buffer_x, buffer_y;
4773
4774           gtk_text_view_window_to_buffer_coords (text_view,
4775                                                  GTK_TEXT_WINDOW_TEXT,
4776                                                  priv->drag_start_x,
4777                                                  priv->drag_start_y,
4778                                                  &buffer_x,
4779                                                  &buffer_y);
4780
4781           gtk_text_layout_get_iter_at_pixel (priv->layout,
4782                                              &iter,
4783                                              buffer_x, buffer_y);
4784
4785           gtk_text_view_start_selection_dnd (text_view, &iter, event);
4786           return TRUE;
4787         }
4788     }
4789
4790   return FALSE;
4791 }
4792
4793 static void
4794 gtk_text_view_paint (GtkWidget      *widget,
4795                      cairo_t        *cr)
4796 {
4797   GtkTextView *text_view;
4798   GtkTextViewPrivate *priv;
4799   GList *child_exposes;
4800   GList *tmp_list;
4801   
4802   text_view = GTK_TEXT_VIEW (widget);
4803   priv = text_view->priv;
4804
4805   g_return_if_fail (priv->layout != NULL);
4806   g_return_if_fail (priv->xoffset >= 0);
4807   g_return_if_fail (priv->yoffset >= 0);
4808
4809   while (priv->first_validate_idle != 0)
4810     {
4811       DV (g_print (G_STRLOC": first_validate_idle: %d\n",
4812                    priv->first_validate_idle));
4813       gtk_text_view_flush_first_validate (text_view);
4814     }
4815
4816   if (!priv->onscreen_validated)
4817     {
4818       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.");
4819       g_assert_not_reached ();
4820     }
4821   
4822 #if 0
4823   printf ("painting %d,%d  %d x %d\n",
4824           area->x, area->y,
4825           area->width, area->height);
4826 #endif
4827
4828   child_exposes = NULL;
4829
4830   cairo_save (cr);
4831   cairo_translate (cr, -priv->xoffset, -priv->yoffset);
4832
4833   gtk_text_layout_draw (priv->layout,
4834                         widget,
4835                         cr,
4836                         &child_exposes);
4837
4838   cairo_restore (cr);
4839
4840   tmp_list = child_exposes;
4841   while (tmp_list != NULL)
4842     {
4843       GtkWidget *child = tmp_list->data;
4844   
4845       gtk_container_propagate_draw (GTK_CONTAINER (text_view),
4846                                     child,
4847                                     cr);
4848
4849       g_object_unref (child);
4850       
4851       tmp_list = tmp_list->next;
4852     }
4853
4854   g_list_free (child_exposes);
4855 }
4856
4857 static gboolean
4858 gtk_text_view_draw (GtkWidget *widget,
4859                     cairo_t   *cr)
4860 {
4861   GSList *tmp_list;
4862   GdkWindow *window;
4863   
4864   if (gtk_cairo_should_draw_window (cr, gtk_widget_get_window (widget)))
4865     gtk_text_view_draw_focus (widget, cr);
4866
4867   window = gtk_text_view_get_window (GTK_TEXT_VIEW (widget),
4868                                      GTK_TEXT_WINDOW_TEXT);
4869   if (gtk_cairo_should_draw_window (cr, window))
4870     {
4871       DV(g_print (">Exposed ("G_STRLOC")\n"));
4872       cairo_save (cr);
4873       gtk_cairo_transform_to_window (cr, widget, window);
4874       gtk_text_view_paint (widget, cr);
4875       cairo_restore (cr);
4876     }
4877
4878   /* Propagate exposes to all unanchored children. 
4879    * Anchored children are handled in gtk_text_view_paint(). 
4880    */
4881   tmp_list = GTK_TEXT_VIEW (widget)->priv->children;
4882   while (tmp_list != NULL)
4883     {
4884       GtkTextViewChild *vc = tmp_list->data;
4885
4886       /* propagate_draw checks that event->window matches
4887        * child->window
4888        */
4889       if (!vc->anchor)
4890         gtk_container_propagate_draw (GTK_CONTAINER (widget),
4891                                       vc->widget,
4892                                       cr);
4893       
4894       tmp_list = tmp_list->next;
4895     }
4896   
4897   return FALSE;
4898 }
4899
4900 static void
4901 gtk_text_view_draw_focus (GtkWidget *widget,
4902                           cairo_t   *cr)
4903 {
4904   gboolean interior_focus;
4905
4906   /* We clear the focus if we are in interior focus mode. */
4907   gtk_widget_style_get (widget,
4908                         "interior-focus", &interior_focus,
4909                         NULL);
4910   
4911   if (gtk_widget_has_visible_focus (widget) && !interior_focus)
4912     {
4913       GtkStyleContext *context;
4914
4915       context = gtk_widget_get_style_context (widget);
4916
4917       gtk_render_focus (context, cr, 0, 0,
4918                         gtk_widget_get_allocated_width (widget),
4919                         gtk_widget_get_allocated_height (widget));
4920     }
4921 }
4922
4923 static gboolean
4924 gtk_text_view_focus (GtkWidget        *widget,
4925                      GtkDirectionType  direction)
4926 {
4927   GtkContainer *container;
4928   gboolean result;
4929   
4930   container = GTK_CONTAINER (widget);  
4931
4932   if (!gtk_widget_is_focus (widget) &&
4933       gtk_container_get_focus_child (container) == NULL)
4934     {
4935       gtk_widget_grab_focus (widget);
4936       return TRUE;
4937     }
4938   else
4939     {
4940       /*
4941        * Unset CAN_FOCUS flag so that gtk_container_focus() allows
4942        * children to get the focus
4943        */
4944       gtk_widget_set_can_focus (widget, FALSE);
4945       result = GTK_WIDGET_CLASS (gtk_text_view_parent_class)->focus (widget, direction);
4946       gtk_widget_set_can_focus (widget, TRUE);
4947
4948       return result;
4949     }
4950 }
4951
4952 /*
4953  * Container
4954  */
4955
4956 static void
4957 gtk_text_view_add (GtkContainer *container,
4958                    GtkWidget    *child)
4959 {
4960   /* This is pretty random. */
4961   gtk_text_view_add_child_in_window (GTK_TEXT_VIEW (container),
4962                                      child,
4963                                      GTK_TEXT_WINDOW_WIDGET,
4964                                      0, 0);
4965 }
4966
4967 static void
4968 gtk_text_view_remove (GtkContainer *container,
4969                       GtkWidget    *child)
4970 {
4971   GtkTextView *text_view;
4972   GtkTextViewPrivate *priv;
4973   GtkTextViewChild *vc;
4974   GSList *iter;
4975
4976   text_view = GTK_TEXT_VIEW (container);
4977   priv = text_view->priv;
4978
4979   vc = NULL;
4980   iter = priv->children;
4981
4982   while (iter != NULL)
4983     {
4984       vc = iter->data;
4985
4986       if (vc->widget == child)
4987         break;
4988
4989       iter = g_slist_next (iter);
4990     }
4991
4992   g_assert (iter != NULL); /* be sure we had the child in the list */
4993
4994   priv->children = g_slist_remove (priv->children, vc);
4995
4996   gtk_widget_unparent (vc->widget);
4997
4998   text_view_child_free (vc);
4999 }
5000
5001 static void
5002 gtk_text_view_forall (GtkContainer *container,
5003                       gboolean      include_internals,
5004                       GtkCallback   callback,
5005                       gpointer      callback_data)
5006 {
5007   GSList *iter;
5008   GtkTextView *text_view;
5009   GSList *copy;
5010
5011   g_return_if_fail (GTK_IS_TEXT_VIEW (container));
5012   g_return_if_fail (callback != NULL);
5013
5014   text_view = GTK_TEXT_VIEW (container);
5015
5016   copy = g_slist_copy (text_view->priv->children);
5017   iter = copy;
5018
5019   while (iter != NULL)
5020     {
5021       GtkTextViewChild *vc = iter->data;
5022
5023       (* callback) (vc->widget, callback_data);
5024
5025       iter = g_slist_next (iter);
5026     }
5027
5028   g_slist_free (copy);
5029 }
5030
5031 #define CURSOR_ON_MULTIPLIER 2
5032 #define CURSOR_OFF_MULTIPLIER 1
5033 #define CURSOR_PEND_MULTIPLIER 3
5034 #define CURSOR_DIVIDER 3
5035
5036 static gboolean
5037 cursor_blinks (GtkTextView *text_view)
5038 {
5039   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5040   gboolean blink;
5041
5042 #ifdef DEBUG_VALIDATION_AND_SCROLLING
5043   return FALSE;
5044 #endif
5045   if (gtk_get_debug_flags () & GTK_DEBUG_UPDATES)
5046     return FALSE;
5047
5048   g_object_get (settings, "gtk-cursor-blink", &blink, NULL);
5049
5050   if (!blink)
5051     return FALSE;
5052
5053   if (text_view->priv->editable)
5054     {
5055       GtkTextMark *insert;
5056       GtkTextIter iter;
5057       
5058       insert = gtk_text_buffer_get_insert (get_buffer (text_view));
5059       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
5060       
5061       if (gtk_text_iter_editable (&iter, text_view->priv->editable))
5062         return blink;
5063     }
5064
5065   return FALSE;
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   /* process exposes */
7696   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
7697     {
7698       DV (g_print ("Processing updates (%s)\n", G_STRLOC));
7699       
7700       if (priv->left_window)
7701         gdk_window_process_updates (priv->left_window->bin_window, TRUE);
7702
7703       if (priv->right_window)
7704         gdk_window_process_updates (priv->right_window->bin_window, TRUE);
7705
7706       if (priv->top_window)
7707         gdk_window_process_updates (priv->top_window->bin_window, TRUE);
7708       
7709       if (priv->bottom_window)
7710         gdk_window_process_updates (priv->bottom_window->bin_window, TRUE);
7711   
7712       gdk_window_process_updates (priv->text_window->bin_window, TRUE);
7713     }
7714
7715   /* If this got installed, get rid of it, it's just a waste of time. */
7716   if (priv->first_validate_idle != 0)
7717     {
7718       g_source_remove (priv->first_validate_idle);
7719       priv->first_validate_idle = 0;
7720     }
7721
7722   /* Finally we update the IM cursor location again, to ensure any
7723    * changes made by the validation are pushed through.
7724    */
7725   gtk_text_view_update_im_spot_location (text_view);
7726   
7727   DV(g_print(">End scroll offset changed handler ("G_STRLOC")\n"));
7728 }
7729
7730 static void
7731 gtk_text_view_commit_handler (GtkIMContext  *context,
7732                               const gchar   *str,
7733                               GtkTextView   *text_view)
7734 {
7735   gtk_text_view_commit_text (text_view, str);
7736 }
7737
7738 static void
7739 gtk_text_view_commit_text (GtkTextView   *text_view,
7740                            const gchar   *str)
7741 {
7742   GtkTextViewPrivate *priv;
7743   gboolean had_selection;
7744
7745   priv = text_view->priv;
7746
7747   gtk_text_buffer_begin_user_action (get_buffer (text_view));
7748
7749   had_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
7750                                                         NULL, NULL);
7751   
7752   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
7753                                     priv->editable);
7754
7755   if (!strcmp (str, "\n"))
7756     {
7757       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), "\n", 1,
7758                                                          priv->editable))
7759         {
7760           gtk_widget_error_bell (GTK_WIDGET (text_view));
7761         }
7762     }
7763   else
7764     {
7765       if (!had_selection && priv->overwrite_mode)
7766         {
7767           GtkTextIter insert;
7768
7769           gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
7770                                             &insert,
7771                                             gtk_text_buffer_get_insert (get_buffer (text_view)));
7772           if (!gtk_text_iter_ends_line (&insert))
7773             gtk_text_view_delete_from_cursor (text_view, GTK_DELETE_CHARS, 1);
7774         }
7775
7776       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
7777                                                          priv->editable))
7778         {
7779           gtk_widget_error_bell (GTK_WIDGET (text_view));
7780         }
7781     }
7782
7783   gtk_text_buffer_end_user_action (get_buffer (text_view));
7784
7785   gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
7786   DV(g_print (G_STRLOC": scrolling onscreen\n"));
7787   gtk_text_view_scroll_mark_onscreen (text_view,
7788                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
7789 }
7790
7791 static void
7792 gtk_text_view_preedit_changed_handler (GtkIMContext *context,
7793                                        GtkTextView  *text_view)
7794 {
7795   GtkTextViewPrivate *priv;
7796   gchar *str;
7797   PangoAttrList *attrs;
7798   gint cursor_pos;
7799   GtkTextIter iter;
7800
7801   priv = text_view->priv;
7802
7803   gtk_text_buffer_get_iter_at_mark (priv->buffer, &iter,
7804                                     gtk_text_buffer_get_insert (priv->buffer));
7805
7806   /* Keypress events are passed to input method even if cursor position is
7807    * not editable; so beep here if it's multi-key input sequence, input
7808    * method will be reset in key-press-event handler.
7809    */
7810   gtk_im_context_get_preedit_string (context, &str, &attrs, &cursor_pos);
7811
7812   if (str && str[0] && !gtk_text_iter_can_insert (&iter, priv->editable))
7813     {
7814       gtk_widget_error_bell (GTK_WIDGET (text_view));
7815       goto out;
7816     }
7817
7818   g_signal_emit (text_view, signals[PREEDIT_CHANGED], 0, str);
7819
7820   if (priv->layout)
7821     gtk_text_layout_set_preedit_string (priv->layout, str, attrs, cursor_pos);
7822   if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
7823     gtk_text_view_scroll_mark_onscreen (text_view,
7824                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
7825
7826 out:
7827   pango_attr_list_unref (attrs);
7828   g_free (str);
7829 }
7830
7831 static gboolean
7832 gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
7833                                             GtkTextView   *text_view)
7834 {
7835   GtkTextIter start;
7836   GtkTextIter end;
7837   gint pos;
7838   gchar *text;
7839
7840   gtk_text_buffer_get_iter_at_mark (text_view->priv->buffer, &start,
7841                                     gtk_text_buffer_get_insert (text_view->priv->buffer));
7842   end = start;
7843
7844   pos = gtk_text_iter_get_line_index (&start);
7845   gtk_text_iter_set_line_offset (&start, 0);
7846   gtk_text_iter_forward_to_line_end (&end);
7847
7848   text = gtk_text_iter_get_slice (&start, &end);
7849   gtk_im_context_set_surrounding (context, text, -1, pos);
7850   g_free (text);
7851
7852   return TRUE;
7853 }
7854
7855 static gboolean
7856 gtk_text_view_delete_surrounding_handler (GtkIMContext  *context,
7857                                           gint           offset,
7858                                           gint           n_chars,
7859                                           GtkTextView   *text_view)
7860 {
7861   GtkTextViewPrivate *priv;
7862   GtkTextIter start;
7863   GtkTextIter end;
7864
7865   priv = text_view->priv;
7866
7867   gtk_text_buffer_get_iter_at_mark (priv->buffer, &start,
7868                                     gtk_text_buffer_get_insert (priv->buffer));
7869   end = start;
7870
7871   gtk_text_iter_forward_chars (&start, offset);
7872   gtk_text_iter_forward_chars (&end, offset + n_chars);
7873
7874   gtk_text_buffer_delete_interactive (priv->buffer, &start, &end,
7875                                       priv->editable);
7876
7877   return TRUE;
7878 }
7879
7880 static void
7881 gtk_text_view_mark_set_handler (GtkTextBuffer     *buffer,
7882                                 const GtkTextIter *location,
7883                                 GtkTextMark       *mark,
7884                                 gpointer           data)
7885 {
7886   GtkTextView *text_view = GTK_TEXT_VIEW (data);
7887   gboolean need_reset = FALSE;
7888
7889   if (mark == gtk_text_buffer_get_insert (buffer))
7890     {
7891       text_view->priv->virtual_cursor_x = -1;
7892       text_view->priv->virtual_cursor_y = -1;
7893       gtk_text_view_update_im_spot_location (text_view);
7894       need_reset = TRUE;
7895     }
7896   else if (mark == gtk_text_buffer_get_selection_bound (buffer))
7897     {
7898       need_reset = TRUE;
7899     }
7900
7901   if (need_reset)
7902     gtk_text_view_reset_im_context (text_view);
7903 }
7904
7905 static void
7906 gtk_text_view_target_list_notify (GtkTextBuffer    *buffer,
7907                                   const GParamSpec *pspec,
7908                                   gpointer          data)
7909 {
7910   GtkWidget     *widget = GTK_WIDGET (data);
7911   GtkTargetList *view_list;
7912   GtkTargetList *buffer_list;
7913   GList         *list;
7914
7915   view_list = gtk_drag_dest_get_target_list (widget);
7916   buffer_list = gtk_text_buffer_get_paste_target_list (buffer);
7917
7918   if (view_list)
7919     gtk_target_list_ref (view_list);
7920   else
7921     view_list = gtk_target_list_new (NULL, 0);
7922
7923   list = view_list->list;
7924   while (list)
7925     {
7926       GtkTargetPair *pair = list->data;
7927
7928       list = g_list_next (list); /* get next element before removing */
7929
7930       if (pair->info >= GTK_TEXT_BUFFER_TARGET_INFO_TEXT &&
7931           pair->info <= GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
7932         {
7933           gtk_target_list_remove (view_list, pair->target);
7934         }
7935     }
7936
7937   for (list = buffer_list->list; list; list = g_list_next (list))
7938     {
7939       GtkTargetPair *pair = list->data;
7940
7941       gtk_target_list_add (view_list, pair->target, pair->flags, pair->info);
7942     }
7943
7944   gtk_drag_dest_set_target_list (widget, view_list);
7945   gtk_target_list_unref (view_list);
7946 }
7947
7948 static void
7949 gtk_text_view_get_virtual_cursor_pos (GtkTextView *text_view,
7950                                       GtkTextIter *cursor,
7951                                       gint        *x,
7952                                       gint        *y)
7953 {
7954   GtkTextViewPrivate *priv;
7955   GtkTextIter insert;
7956   GdkRectangle pos;
7957
7958   priv = text_view->priv;
7959
7960   if (cursor)
7961     insert = *cursor;
7962   else
7963     gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
7964                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
7965
7966   if ((x && priv->virtual_cursor_x == -1) ||
7967       (y && priv->virtual_cursor_y == -1))
7968     gtk_text_layout_get_cursor_locations (priv->layout, &insert, &pos, NULL);
7969
7970   if (x)
7971     {
7972       if (priv->virtual_cursor_x != -1)
7973         *x = priv->virtual_cursor_x;
7974       else
7975         *x = pos.x;
7976     }
7977
7978   if (y)
7979     {
7980       if (priv->virtual_cursor_x != -1)
7981         *y = priv->virtual_cursor_y;
7982       else
7983         *y = pos.y + pos.height / 2;
7984     }
7985 }
7986
7987 static void
7988 gtk_text_view_set_virtual_cursor_pos (GtkTextView *text_view,
7989                                       gint         x,
7990                                       gint         y)
7991 {
7992   GdkRectangle pos;
7993
7994   if (!text_view->priv->layout)
7995     return;
7996
7997   if (x == -1 || y == -1)
7998     gtk_text_view_get_cursor_locations (text_view, NULL, &pos, NULL);
7999
8000   text_view->priv->virtual_cursor_x = (x == -1) ? pos.x : x;
8001   text_view->priv->virtual_cursor_y = (y == -1) ? pos.y + pos.height / 2 : y;
8002 }
8003
8004 /* Quick hack of a popup menu
8005  */
8006 static void
8007 activate_cb (GtkWidget   *menuitem,
8008              GtkTextView *text_view)
8009 {
8010   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
8011   g_signal_emit_by_name (text_view, signal);
8012 }
8013
8014 static void
8015 append_action_signal (GtkTextView  *text_view,
8016                       GtkWidget    *menu,
8017                       const gchar  *stock_id,
8018                       const gchar  *signal,
8019                       gboolean      sensitive)
8020 {
8021   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
8022
8023   g_object_set_data (G_OBJECT (menuitem), I_("gtk-signal"), (char *)signal);
8024   g_signal_connect (menuitem, "activate",
8025                     G_CALLBACK (activate_cb), text_view);
8026
8027   gtk_widget_set_sensitive (menuitem, sensitive);
8028   
8029   gtk_widget_show (menuitem);
8030   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
8031 }
8032
8033 static void
8034 gtk_text_view_select_all (GtkWidget *widget,
8035                           gboolean select)
8036 {
8037   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
8038   GtkTextBuffer *buffer;
8039   GtkTextIter start_iter, end_iter, insert;
8040
8041   buffer = text_view->priv->buffer;
8042   if (select) 
8043     {
8044       gtk_text_buffer_get_bounds (buffer, &start_iter, &end_iter);
8045       gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
8046     }
8047   else 
8048     {
8049       gtk_text_buffer_get_iter_at_mark (buffer, &insert,
8050                                         gtk_text_buffer_get_insert (buffer));
8051       gtk_text_buffer_move_mark_by_name (buffer, "selection_bound", &insert);
8052     }
8053 }
8054
8055 static void
8056 select_all_cb (GtkWidget   *menuitem,
8057                GtkTextView *text_view)
8058 {
8059   gtk_text_view_select_all (GTK_WIDGET (text_view), TRUE);
8060 }
8061
8062 static void
8063 delete_cb (GtkTextView *text_view)
8064 {
8065   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
8066                                     text_view->priv->editable);
8067 }
8068
8069 static void
8070 popup_menu_detach (GtkWidget *attach_widget,
8071                    GtkMenu   *menu)
8072 {
8073   GTK_TEXT_VIEW (attach_widget)->priv->popup_menu = NULL;
8074 }
8075
8076 static void
8077 popup_position_func (GtkMenu   *menu,
8078                      gint      *x,
8079                      gint      *y,
8080                      gboolean  *push_in,
8081                      gpointer   user_data)
8082 {
8083   GtkAllocation allocation;
8084   GtkTextView *text_view;
8085   GtkWidget *widget;
8086   GdkRectangle cursor_rect;
8087   GdkRectangle onscreen_rect;
8088   gint root_x, root_y;
8089   GtkTextIter iter;
8090   GtkRequisition req;      
8091   GdkScreen *screen;
8092   gint monitor_num;
8093   GdkRectangle monitor;
8094       
8095   text_view = GTK_TEXT_VIEW (user_data);
8096   widget = GTK_WIDGET (text_view);
8097   
8098   g_return_if_fail (gtk_widget_get_realized (widget));
8099   
8100   screen = gtk_widget_get_screen (widget);
8101
8102   gdk_window_get_origin (gtk_widget_get_window (widget),
8103                          &root_x, &root_y);
8104
8105   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8106                                     &iter,
8107                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
8108
8109   gtk_text_view_get_iter_location (text_view,
8110                                    &iter,
8111                                    &cursor_rect);
8112
8113   gtk_text_view_get_visible_rect (text_view, &onscreen_rect);
8114
8115   gtk_widget_get_preferred_size (text_view->priv->popup_menu,
8116                                  &req, NULL);
8117
8118   gtk_widget_get_allocation (widget, &allocation);
8119
8120   /* can't use rectangle_intersect since cursor rect can have 0 width */
8121   if (cursor_rect.x >= onscreen_rect.x &&
8122       cursor_rect.x < onscreen_rect.x + onscreen_rect.width &&
8123       cursor_rect.y >= onscreen_rect.y &&
8124       cursor_rect.y < onscreen_rect.y + onscreen_rect.height)
8125     {    
8126       gtk_text_view_buffer_to_window_coords (text_view,
8127                                              GTK_TEXT_WINDOW_WIDGET,
8128                                              cursor_rect.x, cursor_rect.y,
8129                                              &cursor_rect.x, &cursor_rect.y);
8130
8131       *x = root_x + cursor_rect.x + cursor_rect.width;
8132       *y = root_y + cursor_rect.y + cursor_rect.height;
8133     }
8134   else
8135     {
8136       /* Just center the menu, since cursor is offscreen. */
8137       *x = root_x + (allocation.width / 2 - req.width / 2);
8138       *y = root_y + (allocation.height / 2 - req.height / 2);
8139     }
8140
8141   /* Ensure sanity */
8142   *x = CLAMP (*x, root_x, (root_x + allocation.width));
8143   *y = CLAMP (*y, root_y, (root_y + allocation.height));
8144
8145   monitor_num = gdk_screen_get_monitor_at_point (screen, *x, *y);
8146   gtk_menu_set_monitor (menu, monitor_num);
8147   gdk_screen_get_monitor_geometry (screen, monitor_num, &monitor);
8148
8149   *x = CLAMP (*x, monitor.x, monitor.x + MAX (0, monitor.width - req.width));
8150   *y = CLAMP (*y, monitor.y, monitor.y + MAX (0, monitor.height - req.height));
8151
8152   *push_in = FALSE;
8153 }
8154
8155 typedef struct
8156 {
8157   GtkTextView *text_view;
8158   gint button;
8159   guint time;
8160   GdkDevice *device;
8161 } PopupInfo;
8162
8163 static gboolean
8164 range_contains_editable_text (const GtkTextIter *start,
8165                               const GtkTextIter *end,
8166                               gboolean default_editability)
8167 {
8168   GtkTextIter iter = *start;
8169
8170   while (gtk_text_iter_compare (&iter, end) < 0)
8171     {
8172       if (gtk_text_iter_editable (&iter, default_editability))
8173         return TRUE;
8174       
8175       gtk_text_iter_forward_to_tag_toggle (&iter, NULL);
8176     }
8177
8178   return FALSE;
8179 }                             
8180
8181 static void
8182 unichar_chosen_func (const char *text,
8183                      gpointer    data)
8184 {
8185   GtkTextView *text_view = GTK_TEXT_VIEW (data);
8186
8187   gtk_text_view_commit_text (text_view, text);
8188 }
8189
8190 static void
8191 popup_targets_received (GtkClipboard     *clipboard,
8192                         GtkSelectionData *data,
8193                         gpointer          user_data)
8194 {
8195   PopupInfo *info = user_data;
8196   GtkTextView *text_view;
8197   GtkTextViewPrivate *priv;
8198
8199   text_view = info->text_view;
8200   priv = text_view->priv;
8201
8202   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
8203     {
8204       /* We implicitely rely here on the fact that if we are pasting ourself, we'll
8205        * have text targets as well as the private GTK_TEXT_BUFFER_CONTENTS target.
8206        */
8207       gboolean clipboard_contains_text;
8208       GtkWidget *menuitem;
8209       GtkWidget *submenu;
8210       gboolean have_selection;
8211       gboolean can_insert;
8212       GtkTextIter iter;
8213       GtkTextIter sel_start, sel_end;
8214       gboolean show_input_method_menu;
8215       gboolean show_unicode_menu;
8216       
8217       clipboard_contains_text = gtk_selection_data_targets_include_text (data);
8218
8219       if (priv->popup_menu)
8220         gtk_widget_destroy (priv->popup_menu);
8221
8222       priv->popup_menu = gtk_menu_new ();
8223       
8224       gtk_menu_attach_to_widget (GTK_MENU (priv->popup_menu),
8225                                  GTK_WIDGET (text_view),
8226                                  popup_menu_detach);
8227       
8228       have_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
8229                                                              &sel_start, &sel_end);
8230       
8231       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8232                                         &iter,
8233                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
8234       
8235       can_insert = gtk_text_iter_can_insert (&iter, priv->editable);
8236       
8237       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_CUT, "cut-clipboard",
8238                             have_selection &&
8239                             range_contains_editable_text (&sel_start, &sel_end,
8240                                                           priv->editable));
8241       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_COPY, "copy-clipboard",
8242                             have_selection);
8243       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_PASTE, "paste-clipboard",
8244                             can_insert && clipboard_contains_text);
8245       
8246       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
8247       gtk_widget_set_sensitive (menuitem, 
8248                                 have_selection &&
8249                                 range_contains_editable_text (&sel_start, &sel_end,
8250                                                               priv->editable));
8251       g_signal_connect_swapped (menuitem, "activate",
8252                                 G_CALLBACK (delete_cb), text_view);
8253       gtk_widget_show (menuitem);
8254       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8255
8256       menuitem = gtk_separator_menu_item_new ();
8257       gtk_widget_show (menuitem);
8258       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8259
8260       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_SELECT_ALL, NULL);
8261       gtk_widget_set_sensitive (menuitem,
8262                                 gtk_text_buffer_get_char_count (priv->buffer) > 0);
8263       g_signal_connect (menuitem, "activate",
8264                         G_CALLBACK (select_all_cb), text_view);
8265       gtk_widget_show (menuitem);
8266       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8267
8268       g_object_get (gtk_widget_get_settings (GTK_WIDGET (text_view)),
8269                     "gtk-show-input-method-menu", &show_input_method_menu,
8270                     "gtk-show-unicode-menu", &show_unicode_menu,
8271                     NULL);
8272       
8273       if (show_input_method_menu || show_unicode_menu)
8274         {
8275           menuitem = gtk_separator_menu_item_new ();
8276           gtk_widget_show (menuitem);
8277           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8278         }
8279
8280       if (show_input_method_menu)
8281         {
8282           menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
8283           gtk_widget_show (menuitem);
8284           gtk_widget_set_sensitive (menuitem, can_insert);
8285
8286           submenu = gtk_menu_new ();
8287           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
8288           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8289           
8290           gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (priv->im_context),
8291                                                 GTK_MENU_SHELL (submenu));
8292         }
8293
8294       if (show_unicode_menu)
8295         {
8296           menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode Control Character"));
8297           gtk_widget_show (menuitem);
8298           gtk_widget_set_sensitive (menuitem, can_insert);
8299       
8300           submenu = gtk_menu_new ();
8301           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
8302           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8303           
8304           _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
8305                                                         unichar_chosen_func,
8306                                                         text_view);
8307         }
8308           
8309       g_signal_emit (text_view,
8310                      signals[POPULATE_POPUP],
8311                      0,
8312                      priv->popup_menu);
8313       
8314       if (info->device)
8315         gtk_menu_popup_for_device (GTK_MENU (priv->popup_menu), 
8316       info->device, NULL, NULL, NULL, NULL, NULL,
8317                         info->button, info->time);
8318       else
8319         {
8320           gtk_menu_popup (GTK_MENU (priv->popup_menu), NULL, NULL,
8321                           popup_position_func, text_view,
8322                           0, gtk_get_current_event_time ());
8323           gtk_menu_shell_select_first (GTK_MENU_SHELL (priv->popup_menu), FALSE);
8324         }
8325     }
8326
8327   g_object_unref (text_view);
8328   g_free (info);
8329 }
8330
8331 static void
8332 gtk_text_view_do_popup (GtkTextView    *text_view,
8333                         GdkEventButton *event)
8334 {
8335   PopupInfo *info = g_new (PopupInfo, 1);
8336
8337   /* In order to know what entries we should make sensitive, we
8338    * ask for the current targets of the clipboard, and when
8339    * we get them, then we actually pop up the menu.
8340    */
8341   info->text_view = g_object_ref (text_view);
8342   
8343   if (event)
8344     {
8345       info->button = event->button;
8346       info->time = event->time;
8347       info->device = event->device;
8348     }
8349   else
8350     {
8351       info->button = 0;
8352       info->time = gtk_get_current_event_time ();
8353       info->device = NULL;
8354     }
8355
8356   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (text_view),
8357                                                             GDK_SELECTION_CLIPBOARD),
8358                                   gdk_atom_intern_static_string ("TARGETS"),
8359                                   popup_targets_received,
8360                                   info);
8361 }
8362
8363 static gboolean
8364 gtk_text_view_popup_menu (GtkWidget *widget)
8365 {
8366   gtk_text_view_do_popup (GTK_TEXT_VIEW (widget), NULL);  
8367   return TRUE;
8368 }
8369
8370 /* Child GdkWindows */
8371
8372
8373 static GtkTextWindow*
8374 text_window_new (GtkTextWindowType  type,
8375                  GtkWidget         *widget,
8376                  gint               width_request,
8377                  gint               height_request)
8378 {
8379   GtkTextWindow *win;
8380
8381   win = g_new (GtkTextWindow, 1);
8382
8383   win->type = type;
8384   win->widget = widget;
8385   win->window = NULL;
8386   win->bin_window = NULL;
8387   win->requisition.width = width_request;
8388   win->requisition.height = height_request;
8389   win->allocation.width = width_request;
8390   win->allocation.height = height_request;
8391   win->allocation.x = 0;
8392   win->allocation.y = 0;
8393
8394   return win;
8395 }
8396
8397 static void
8398 text_window_free (GtkTextWindow *win)
8399 {
8400   if (win->window)
8401     text_window_unrealize (win);
8402
8403   g_free (win);
8404 }
8405
8406 static void
8407 text_window_realize (GtkTextWindow *win,
8408                      GtkWidget     *widget)
8409 {
8410   GtkStyleContext *context;
8411   GtkStateFlags state;
8412   GdkWindow *window;
8413   GdkWindowAttr attributes;
8414   gint attributes_mask;
8415   GdkCursor *cursor;
8416   GdkRGBA color;
8417
8418   attributes.window_type = GDK_WINDOW_CHILD;
8419   attributes.x = win->allocation.x;
8420   attributes.y = win->allocation.y;
8421   attributes.width = win->allocation.width;
8422   attributes.height = win->allocation.height;
8423   attributes.wclass = GDK_INPUT_OUTPUT;
8424   attributes.visual = gtk_widget_get_visual (win->widget);
8425   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK;
8426
8427   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
8428
8429   window = gtk_widget_get_window (widget);
8430
8431   win->window = gdk_window_new (window,
8432                                 &attributes, attributes_mask);
8433
8434   gdk_window_show (win->window);
8435   gdk_window_set_user_data (win->window, win->widget);
8436   gdk_window_lower (win->window);
8437
8438   attributes.x = 0;
8439   attributes.y = 0;
8440   attributes.width = win->allocation.width;
8441   attributes.height = win->allocation.height;
8442   attributes.event_mask = (GDK_EXPOSURE_MASK            |
8443                            GDK_SCROLL_MASK              |
8444                            GDK_KEY_PRESS_MASK           |
8445                            GDK_BUTTON_PRESS_MASK        |
8446                            GDK_BUTTON_RELEASE_MASK      |
8447                            GDK_POINTER_MOTION_MASK      |
8448                            GDK_POINTER_MOTION_HINT_MASK |
8449                            gtk_widget_get_events (win->widget));
8450
8451   win->bin_window = gdk_window_new (win->window,
8452                                     &attributes,
8453                                     attributes_mask);
8454
8455   gdk_window_show (win->bin_window);
8456   gdk_window_set_user_data (win->bin_window, win->widget);
8457
8458   context = gtk_widget_get_style_context (widget);
8459   state = gtk_widget_get_state_flags (widget);
8460
8461   if (win->type == GTK_TEXT_WINDOW_TEXT)
8462     {
8463       if (gtk_widget_is_sensitive (widget))
8464         {
8465           /* I-beam cursor */
8466           cursor = gdk_cursor_new_for_display (gdk_window_get_display (window),
8467                                                GDK_XTERM);
8468           gdk_window_set_cursor (win->bin_window, cursor);
8469           g_object_unref (cursor);
8470         } 
8471
8472       gtk_im_context_set_client_window (GTK_TEXT_VIEW (widget)->priv->im_context,
8473                                         win->window);
8474
8475       gtk_style_context_save (context);
8476       gtk_style_context_add_class (context, GTK_STYLE_CLASS_VIEW);
8477
8478       gtk_style_context_get_background_color (context, state, &color);
8479       gdk_window_set_background_rgba (win->bin_window, &color);
8480
8481       gtk_style_context_restore (context);
8482     }
8483   else
8484     {
8485       gtk_style_context_get_background_color (context, state, &color);
8486       gdk_window_set_background_rgba (win->bin_window, &color);
8487     }
8488
8489   g_object_set_qdata (G_OBJECT (win->window),
8490                       g_quark_from_static_string ("gtk-text-view-text-window"),
8491                       win);
8492
8493   g_object_set_qdata (G_OBJECT (win->bin_window),
8494                       g_quark_from_static_string ("gtk-text-view-text-window"),
8495                       win);
8496 }
8497
8498 static void
8499 text_window_unrealize (GtkTextWindow *win)
8500 {
8501   if (win->type == GTK_TEXT_WINDOW_TEXT)
8502     {
8503       gtk_im_context_set_client_window (GTK_TEXT_VIEW (win->widget)->priv->im_context,
8504                                         NULL);
8505     }
8506
8507   gdk_window_set_user_data (win->window, NULL);
8508   gdk_window_set_user_data (win->bin_window, NULL);
8509   gdk_window_destroy (win->bin_window);
8510   gdk_window_destroy (win->window);
8511   win->window = NULL;
8512   win->bin_window = NULL;
8513 }
8514
8515 static void
8516 text_window_size_allocate (GtkTextWindow *win,
8517                            GdkRectangle  *rect)
8518 {
8519   win->allocation = *rect;
8520
8521   if (win->window)
8522     {
8523       gdk_window_move_resize (win->window,
8524                               rect->x, rect->y,
8525                               rect->width, rect->height);
8526
8527       gdk_window_resize (win->bin_window,
8528                          rect->width, rect->height);
8529     }
8530 }
8531
8532 static void
8533 text_window_scroll        (GtkTextWindow *win,
8534                            gint           dx,
8535                            gint           dy)
8536 {
8537   if (dx != 0 || dy != 0)
8538     {
8539       gdk_window_scroll (win->bin_window, dx, dy);
8540     }
8541 }
8542
8543 static void
8544 text_window_invalidate_rect (GtkTextWindow *win,
8545                              GdkRectangle  *rect)
8546 {
8547   GdkRectangle window_rect;
8548
8549   gtk_text_view_buffer_to_window_coords (GTK_TEXT_VIEW (win->widget),
8550                                          win->type,
8551                                          rect->x,
8552                                          rect->y,
8553                                          &window_rect.x,
8554                                          &window_rect.y);
8555
8556   window_rect.width = rect->width;
8557   window_rect.height = rect->height;
8558   
8559   /* Adjust the rect as appropriate */
8560   
8561   switch (win->type)
8562     {
8563     case GTK_TEXT_WINDOW_TEXT:
8564       break;
8565
8566     case GTK_TEXT_WINDOW_LEFT:
8567     case GTK_TEXT_WINDOW_RIGHT:
8568       window_rect.x = 0;
8569       window_rect.width = win->allocation.width;
8570       break;
8571
8572     case GTK_TEXT_WINDOW_TOP:
8573     case GTK_TEXT_WINDOW_BOTTOM:
8574       window_rect.y = 0;
8575       window_rect.height = win->allocation.height;
8576       break;
8577
8578     default:
8579       g_warning ("%s: bug!", G_STRFUNC);
8580       return;
8581       break;
8582     }
8583           
8584   gdk_window_invalidate_rect (win->bin_window, &window_rect, FALSE);
8585
8586 #if 0
8587   {
8588     cairo_t *cr = gdk_cairo_create (win->bin_window);
8589     gdk_cairo_rectangle (cr, &window_rect);
8590     cairo_set_source_rgb  (cr, 1.0, 0.0, 0.0);  /* red */
8591     cairo_fill (cr);
8592     cairo_destroy (cr);
8593   }
8594 #endif
8595 }
8596
8597 static void
8598 text_window_invalidate_cursors (GtkTextWindow *win)
8599 {
8600   GtkTextView *text_view;
8601   GtkTextViewPrivate *priv;
8602   GtkTextIter  iter;
8603   GdkRectangle strong;
8604   GdkRectangle weak;
8605   gboolean     draw_arrow;
8606   gfloat       cursor_aspect_ratio;
8607   gint         stem_width;
8608   gint         arrow_width;
8609
8610   text_view = GTK_TEXT_VIEW (win->widget);
8611   priv = text_view->priv;
8612
8613   gtk_text_buffer_get_iter_at_mark (priv->buffer, &iter,
8614                                     gtk_text_buffer_get_insert (priv->buffer));
8615
8616   if (_gtk_text_layout_get_block_cursor (priv->layout, &strong))
8617     {
8618       text_window_invalidate_rect (win, &strong);
8619       return;
8620     }
8621
8622   gtk_text_layout_get_cursor_locations (priv->layout, &iter,
8623                                         &strong, &weak);
8624
8625   /* cursor width calculation as in gtkstylecontext.c:draw_insertion_cursor(),
8626    * ignoring the text direction be exposing both sides of the cursor
8627    */
8628
8629   draw_arrow = (strong.x != weak.x || strong.y != weak.y);
8630
8631   gtk_widget_style_get (win->widget,
8632                         "cursor-aspect-ratio", &cursor_aspect_ratio,
8633                         NULL);
8634   
8635   stem_width = strong.height * cursor_aspect_ratio + 1;
8636   arrow_width = stem_width + 1;
8637
8638   strong.width = stem_width;
8639
8640   /* round up to the next even number */
8641   if (stem_width & 1)
8642     stem_width++;
8643
8644   strong.x     -= stem_width / 2;
8645   strong.width += stem_width;
8646
8647   if (draw_arrow)
8648     {
8649       strong.x     -= arrow_width;
8650       strong.width += arrow_width * 2;
8651     }
8652
8653   text_window_invalidate_rect (win, &strong);
8654
8655   if (draw_arrow) /* == have weak */
8656     {
8657       stem_width = weak.height * cursor_aspect_ratio + 1;
8658       arrow_width = stem_width + 1;
8659
8660       weak.width = stem_width;
8661
8662       /* round up to the next even number */
8663       if (stem_width & 1)
8664         stem_width++;
8665
8666       weak.x     -= stem_width / 2;
8667       weak.width += stem_width;
8668
8669       weak.x     -= arrow_width;
8670       weak.width += arrow_width * 2;
8671
8672       text_window_invalidate_rect (win, &weak);
8673     }
8674 }
8675
8676 static gint
8677 text_window_get_width (GtkTextWindow *win)
8678 {
8679   return win->allocation.width;
8680 }
8681
8682 static gint
8683 text_window_get_height (GtkTextWindow *win)
8684 {
8685   return win->allocation.height;
8686 }
8687
8688 /* Windows */
8689
8690
8691 /**
8692  * gtk_text_view_get_window:
8693  * @text_view: a #GtkTextView
8694  * @win: window to get
8695  *
8696  * Retrieves the #GdkWindow corresponding to an area of the text view;
8697  * possible windows include the overall widget window, child windows
8698  * on the left, right, top, bottom, and the window that displays the
8699  * text buffer. Windows are %NULL and nonexistent if their width or
8700  * height is 0, and are nonexistent before the widget has been
8701  * realized.
8702  *
8703  * Return value: (transfer none): a #GdkWindow, or %NULL
8704  **/
8705 GdkWindow*
8706 gtk_text_view_get_window (GtkTextView *text_view,
8707                           GtkTextWindowType win)
8708 {
8709   GtkTextViewPrivate *priv = text_view->priv;
8710
8711   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
8712
8713   switch (win)
8714     {
8715     case GTK_TEXT_WINDOW_WIDGET:
8716       return gtk_widget_get_window (GTK_WIDGET (text_view));
8717       break;
8718
8719     case GTK_TEXT_WINDOW_TEXT:
8720       return priv->text_window->bin_window;
8721       break;
8722
8723     case GTK_TEXT_WINDOW_LEFT:
8724       if (priv->left_window)
8725         return priv->left_window->bin_window;
8726       else
8727         return NULL;
8728       break;
8729
8730     case GTK_TEXT_WINDOW_RIGHT:
8731       if (priv->right_window)
8732         return priv->right_window->bin_window;
8733       else
8734         return NULL;
8735       break;
8736
8737     case GTK_TEXT_WINDOW_TOP:
8738       if (priv->top_window)
8739         return priv->top_window->bin_window;
8740       else
8741         return NULL;
8742       break;
8743
8744     case GTK_TEXT_WINDOW_BOTTOM:
8745       if (priv->bottom_window)
8746         return priv->bottom_window->bin_window;
8747       else
8748         return NULL;
8749       break;
8750
8751     case GTK_TEXT_WINDOW_PRIVATE:
8752       g_warning ("%s: You can't get GTK_TEXT_WINDOW_PRIVATE, it has \"PRIVATE\" in the name because it is private.", G_STRFUNC);
8753       return NULL;
8754       break;
8755     }
8756
8757   g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
8758   return NULL;
8759 }
8760
8761 /**
8762  * gtk_text_view_get_window_type:
8763  * @text_view: a #GtkTextView
8764  * @window: a window type
8765  *
8766  * Usually used to find out which window an event corresponds to.
8767  * If you connect to an event signal on @text_view, this function
8768  * should be called on <literal>event-&gt;window</literal> to
8769  * see which window it was.
8770  *
8771  * Return value: the window type.
8772  **/
8773 GtkTextWindowType
8774 gtk_text_view_get_window_type (GtkTextView *text_view,
8775                                GdkWindow   *window)
8776 {
8777   GtkTextWindow *win;
8778
8779   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
8780   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
8781
8782   if (window == gtk_widget_get_window (GTK_WIDGET (text_view)))
8783     return GTK_TEXT_WINDOW_WIDGET;
8784
8785   win = g_object_get_qdata (G_OBJECT (window),
8786                             g_quark_try_string ("gtk-text-view-text-window"));
8787
8788   if (win)
8789     return win->type;
8790   else
8791     {
8792       return GTK_TEXT_WINDOW_PRIVATE;
8793     }
8794 }
8795
8796 static void
8797 buffer_to_widget (GtkTextView      *text_view,
8798                   gint              buffer_x,
8799                   gint              buffer_y,
8800                   gint             *window_x,
8801                   gint             *window_y)
8802 {
8803   GtkTextViewPrivate *priv = text_view->priv;
8804
8805   if (window_x)
8806     {
8807       *window_x = buffer_x - priv->xoffset;
8808       *window_x += priv->text_window->allocation.x;
8809     }
8810
8811   if (window_y)
8812     {
8813       *window_y = buffer_y - priv->yoffset;
8814       *window_y += priv->text_window->allocation.y;
8815     }
8816 }
8817
8818 static void
8819 widget_to_text_window (GtkTextWindow *win,
8820                        gint           widget_x,
8821                        gint           widget_y,
8822                        gint          *window_x,
8823                        gint          *window_y)
8824 {
8825   if (window_x)
8826     *window_x = widget_x - win->allocation.x;
8827
8828   if (window_y)
8829     *window_y = widget_y - win->allocation.y;
8830 }
8831
8832 static void
8833 buffer_to_text_window (GtkTextView   *text_view,
8834                        GtkTextWindow *win,
8835                        gint           buffer_x,
8836                        gint           buffer_y,
8837                        gint          *window_x,
8838                        gint          *window_y)
8839 {
8840   if (win == NULL)
8841     {
8842       g_warning ("Attempt to convert text buffer coordinates to coordinates "
8843                  "for a nonexistent or private child window of GtkTextView");
8844       return;
8845     }
8846
8847   buffer_to_widget (text_view,
8848                     buffer_x, buffer_y,
8849                     window_x, window_y);
8850
8851   widget_to_text_window (win,
8852                          window_x ? *window_x : 0,
8853                          window_y ? *window_y : 0,
8854                          window_x,
8855                          window_y);
8856 }
8857
8858 /**
8859  * gtk_text_view_buffer_to_window_coords:
8860  * @text_view: a #GtkTextView
8861  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
8862  * @buffer_x: buffer x coordinate
8863  * @buffer_y: buffer y coordinate
8864  * @window_x: (out) (allow-none): window x coordinate return location or %NULL
8865  * @window_y: (out) (allow-none): window y coordinate return location or %NULL
8866  *
8867  * Converts coordinate (@buffer_x, @buffer_y) to coordinates for the window
8868  * @win, and stores the result in (@window_x, @window_y). 
8869  *
8870  * Note that you can't convert coordinates for a nonexisting window (see 
8871  * gtk_text_view_set_border_window_size()).
8872  **/
8873 void
8874 gtk_text_view_buffer_to_window_coords (GtkTextView      *text_view,
8875                                        GtkTextWindowType win,
8876                                        gint              buffer_x,
8877                                        gint              buffer_y,
8878                                        gint             *window_x,
8879                                        gint             *window_y)
8880 {
8881   GtkTextViewPrivate *priv = text_view->priv;
8882
8883   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
8884
8885   switch (win)
8886     {
8887     case GTK_TEXT_WINDOW_WIDGET:
8888       buffer_to_widget (text_view,
8889                         buffer_x, buffer_y,
8890                         window_x, window_y);
8891       break;
8892
8893     case GTK_TEXT_WINDOW_TEXT:
8894       if (window_x)
8895         *window_x = buffer_x - priv->xoffset;
8896       if (window_y)
8897         *window_y = buffer_y - priv->yoffset;
8898       break;
8899
8900     case GTK_TEXT_WINDOW_LEFT:
8901       buffer_to_text_window (text_view,
8902                              priv->left_window,
8903                              buffer_x, buffer_y,
8904                              window_x, window_y);
8905       break;
8906
8907     case GTK_TEXT_WINDOW_RIGHT:
8908       buffer_to_text_window (text_view,
8909                              priv->right_window,
8910                              buffer_x, buffer_y,
8911                              window_x, window_y);
8912       break;
8913
8914     case GTK_TEXT_WINDOW_TOP:
8915       buffer_to_text_window (text_view,
8916                              priv->top_window,
8917                              buffer_x, buffer_y,
8918                              window_x, window_y);
8919       break;
8920
8921     case GTK_TEXT_WINDOW_BOTTOM:
8922       buffer_to_text_window (text_view,
8923                              priv->bottom_window,
8924                              buffer_x, buffer_y,
8925                              window_x, window_y);
8926       break;
8927
8928     case GTK_TEXT_WINDOW_PRIVATE:
8929       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
8930       break;
8931
8932     default:
8933       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
8934       break;
8935     }
8936 }
8937
8938 static void
8939 widget_to_buffer (GtkTextView *text_view,
8940                   gint         widget_x,
8941                   gint         widget_y,
8942                   gint        *buffer_x,
8943                   gint        *buffer_y)
8944 {
8945   GtkTextViewPrivate *priv = text_view->priv;
8946
8947   if (buffer_x)
8948     {
8949       *buffer_x = widget_x + priv->xoffset;
8950       *buffer_x -= priv->text_window->allocation.x;
8951     }
8952
8953   if (buffer_y)
8954     {
8955       *buffer_y = widget_y + priv->yoffset;
8956       *buffer_y -= priv->text_window->allocation.y;
8957     }
8958 }
8959
8960 static void
8961 text_window_to_widget (GtkTextWindow *win,
8962                        gint           window_x,
8963                        gint           window_y,
8964                        gint          *widget_x,
8965                        gint          *widget_y)
8966 {
8967   if (widget_x)
8968     *widget_x = window_x + win->allocation.x;
8969
8970   if (widget_y)
8971     *widget_y = window_y + win->allocation.y;
8972 }
8973
8974 static void
8975 text_window_to_buffer (GtkTextView   *text_view,
8976                        GtkTextWindow *win,
8977                        gint           window_x,
8978                        gint           window_y,
8979                        gint          *buffer_x,
8980                        gint          *buffer_y)
8981 {
8982   if (win == NULL)
8983     {
8984       g_warning ("Attempt to convert GtkTextView buffer coordinates into "
8985                  "coordinates for a nonexistent child window.");
8986       return;
8987     }
8988
8989   text_window_to_widget (win,
8990                          window_x,
8991                          window_y,
8992                          buffer_x,
8993                          buffer_y);
8994
8995   widget_to_buffer (text_view,
8996                     buffer_x ? *buffer_x : 0,
8997                     buffer_y ? *buffer_y : 0,
8998                     buffer_x,
8999                     buffer_y);
9000 }
9001
9002 /**
9003  * gtk_text_view_window_to_buffer_coords:
9004  * @text_view: a #GtkTextView
9005  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
9006  * @window_x: window x coordinate
9007  * @window_y: window y coordinate
9008  * @buffer_x: (out) (allow-none): buffer x coordinate return location or %NULL
9009  * @buffer_y: (out) (allow-none): buffer y coordinate return location or %NULL
9010  *
9011  * Converts coordinates on the window identified by @win to buffer
9012  * coordinates, storing the result in (@buffer_x,@buffer_y).
9013  *
9014  * Note that you can't convert coordinates for a nonexisting window (see 
9015  * gtk_text_view_set_border_window_size()).
9016  **/
9017 void
9018 gtk_text_view_window_to_buffer_coords (GtkTextView      *text_view,
9019                                        GtkTextWindowType win,
9020                                        gint              window_x,
9021                                        gint              window_y,
9022                                        gint             *buffer_x,
9023                                        gint             *buffer_y)
9024 {
9025   GtkTextViewPrivate *priv = text_view->priv;
9026
9027   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9028
9029   switch (win)
9030     {
9031     case GTK_TEXT_WINDOW_WIDGET:
9032       widget_to_buffer (text_view,
9033                         window_x, window_y,
9034                         buffer_x, buffer_y);
9035       break;
9036
9037     case GTK_TEXT_WINDOW_TEXT:
9038       if (buffer_x)
9039         *buffer_x = window_x + priv->xoffset;
9040       if (buffer_y)
9041         *buffer_y = window_y + priv->yoffset;
9042       break;
9043
9044     case GTK_TEXT_WINDOW_LEFT:
9045       text_window_to_buffer (text_view,
9046                              priv->left_window,
9047                              window_x, window_y,
9048                              buffer_x, buffer_y);
9049       break;
9050
9051     case GTK_TEXT_WINDOW_RIGHT:
9052       text_window_to_buffer (text_view,
9053                              priv->right_window,
9054                              window_x, window_y,
9055                              buffer_x, buffer_y);
9056       break;
9057
9058     case GTK_TEXT_WINDOW_TOP:
9059       text_window_to_buffer (text_view,
9060                              priv->top_window,
9061                              window_x, window_y,
9062                              buffer_x, buffer_y);
9063       break;
9064
9065     case GTK_TEXT_WINDOW_BOTTOM:
9066       text_window_to_buffer (text_view,
9067                              priv->bottom_window,
9068                              window_x, window_y,
9069                              buffer_x, buffer_y);
9070       break;
9071
9072     case GTK_TEXT_WINDOW_PRIVATE:
9073       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
9074       break;
9075
9076     default:
9077       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
9078       break;
9079     }
9080 }
9081
9082 static void
9083 set_window_width (GtkTextView      *text_view,
9084                   gint              width,
9085                   GtkTextWindowType type,
9086                   GtkTextWindow   **winp)
9087 {
9088   if (width == 0)
9089     {
9090       if (*winp)
9091         {
9092           text_window_free (*winp);
9093           *winp = NULL;
9094           gtk_widget_queue_resize (GTK_WIDGET (text_view));
9095         }
9096     }
9097   else
9098     {
9099       if (*winp == NULL)
9100         {
9101           *winp = text_window_new (type,
9102                                    GTK_WIDGET (text_view),
9103                                    width, 0);
9104           /* if the widget is already realized we need to realize the child manually */
9105           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9106             text_window_realize (*winp, GTK_WIDGET (text_view));
9107         }
9108       else
9109         {
9110           if ((*winp)->requisition.width == width)
9111             return;
9112
9113           (*winp)->requisition.width = width;
9114         }
9115
9116       gtk_widget_queue_resize (GTK_WIDGET (text_view));
9117     }
9118 }
9119
9120
9121 static void
9122 set_window_height (GtkTextView      *text_view,
9123                    gint              height,
9124                    GtkTextWindowType type,
9125                    GtkTextWindow   **winp)
9126 {
9127   if (height == 0)
9128     {
9129       if (*winp)
9130         {
9131           text_window_free (*winp);
9132           *winp = NULL;
9133           gtk_widget_queue_resize (GTK_WIDGET (text_view));
9134         }
9135     }
9136   else
9137     {
9138       if (*winp == NULL)
9139         {
9140           *winp = text_window_new (type,
9141                                    GTK_WIDGET (text_view),
9142                                    0, height);
9143
9144           /* if the widget is already realized we need to realize the child manually */
9145           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9146             text_window_realize (*winp, GTK_WIDGET (text_view));
9147         }
9148       else
9149         {
9150           if ((*winp)->requisition.height == height)
9151             return;
9152
9153           (*winp)->requisition.height = height;
9154         }
9155
9156       gtk_widget_queue_resize (GTK_WIDGET (text_view));
9157     }
9158 }
9159
9160 /**
9161  * gtk_text_view_set_border_window_size:
9162  * @text_view: a #GtkTextView
9163  * @type: window to affect
9164  * @size: width or height of the window
9165  *
9166  * Sets the width of %GTK_TEXT_WINDOW_LEFT or %GTK_TEXT_WINDOW_RIGHT,
9167  * or the height of %GTK_TEXT_WINDOW_TOP or %GTK_TEXT_WINDOW_BOTTOM.
9168  * Automatically destroys the corresponding window if the size is set
9169  * to 0, and creates the window if the size is set to non-zero.  This
9170  * function can only be used for the "border windows," it doesn't work
9171  * with #GTK_TEXT_WINDOW_WIDGET, #GTK_TEXT_WINDOW_TEXT, or
9172  * #GTK_TEXT_WINDOW_PRIVATE.
9173  **/
9174 void
9175 gtk_text_view_set_border_window_size (GtkTextView      *text_view,
9176                                       GtkTextWindowType type,
9177                                       gint              size)
9178 {
9179   GtkTextViewPrivate *priv = text_view->priv;
9180
9181   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9182   g_return_if_fail (size >= 0);
9183
9184   switch (type)
9185     {
9186     case GTK_TEXT_WINDOW_LEFT:
9187       set_window_width (text_view, size, GTK_TEXT_WINDOW_LEFT,
9188                         &priv->left_window);
9189       break;
9190
9191     case GTK_TEXT_WINDOW_RIGHT:
9192       set_window_width (text_view, size, GTK_TEXT_WINDOW_RIGHT,
9193                         &priv->right_window);
9194       break;
9195
9196     case GTK_TEXT_WINDOW_TOP:
9197       set_window_height (text_view, size, GTK_TEXT_WINDOW_TOP,
9198                          &priv->top_window);
9199       break;
9200
9201     case GTK_TEXT_WINDOW_BOTTOM:
9202       set_window_height (text_view, size, GTK_TEXT_WINDOW_BOTTOM,
9203                          &priv->bottom_window);
9204       break;
9205
9206     default:
9207       g_warning ("Can only set size of left/right/top/bottom border windows with gtk_text_view_set_border_window_size()");
9208       break;
9209     }
9210 }
9211
9212 /**
9213  * gtk_text_view_get_border_window_size:
9214  * @text_view: a #GtkTextView
9215  * @type: window to return size from
9216  *
9217  * Gets the width of the specified border window. See
9218  * gtk_text_view_set_border_window_size().
9219  *
9220  * Return value: width of window
9221  **/
9222 gint
9223 gtk_text_view_get_border_window_size (GtkTextView       *text_view,
9224                                       GtkTextWindowType  type)
9225 {
9226   GtkTextViewPrivate *priv = text_view->priv;
9227
9228   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
9229   
9230   switch (type)
9231     {
9232     case GTK_TEXT_WINDOW_LEFT:
9233       if (priv->left_window)
9234         return priv->left_window->requisition.width;
9235       break;
9236       
9237     case GTK_TEXT_WINDOW_RIGHT:
9238       if (priv->right_window)
9239         return priv->right_window->requisition.width;
9240       break;
9241       
9242     case GTK_TEXT_WINDOW_TOP:
9243       if (priv->top_window)
9244         return priv->top_window->requisition.height;
9245       break;
9246
9247     case GTK_TEXT_WINDOW_BOTTOM:
9248       if (priv->bottom_window)
9249         return priv->bottom_window->requisition.height;
9250       break;
9251       
9252     default:
9253       g_warning ("Can only get size of left/right/top/bottom border windows with gtk_text_view_get_border_window_size()");
9254       break;
9255     }
9256
9257   return 0;
9258 }
9259
9260 /*
9261  * Child widgets
9262  */
9263
9264 static GtkTextViewChild*
9265 text_view_child_new_anchored (GtkWidget          *child,
9266                               GtkTextChildAnchor *anchor,
9267                               GtkTextLayout      *layout)
9268 {
9269   GtkTextViewChild *vc;
9270
9271   vc = g_new (GtkTextViewChild, 1);
9272
9273   vc->type = GTK_TEXT_WINDOW_PRIVATE;
9274   vc->widget = child;
9275   vc->anchor = anchor;
9276
9277   vc->from_top_of_line = 0;
9278   vc->from_left_of_buffer = 0;
9279   
9280   g_object_ref (vc->widget);
9281   g_object_ref (vc->anchor);
9282
9283   g_object_set_data (G_OBJECT (child),
9284                      I_("gtk-text-view-child"),
9285                      vc);
9286
9287   gtk_text_child_anchor_register_child (anchor, child, layout);
9288   
9289   return vc;
9290 }
9291
9292 static GtkTextViewChild*
9293 text_view_child_new_window (GtkWidget          *child,
9294                             GtkTextWindowType   type,
9295                             gint                x,
9296                             gint                y)
9297 {
9298   GtkTextViewChild *vc;
9299
9300   vc = g_new (GtkTextViewChild, 1);
9301
9302   vc->widget = child;
9303   vc->anchor = NULL;
9304
9305   vc->from_top_of_line = 0;
9306   vc->from_left_of_buffer = 0;
9307  
9308   g_object_ref (vc->widget);
9309
9310   vc->type = type;
9311   vc->x = x;
9312   vc->y = y;
9313
9314   g_object_set_data (G_OBJECT (child),
9315                      I_("gtk-text-view-child"),
9316                      vc);
9317   
9318   return vc;
9319 }
9320
9321 static void
9322 text_view_child_free (GtkTextViewChild *child)
9323 {
9324   g_object_set_data (G_OBJECT (child->widget),
9325                      I_("gtk-text-view-child"), NULL);
9326
9327   if (child->anchor)
9328     {
9329       gtk_text_child_anchor_unregister_child (child->anchor,
9330                                               child->widget);
9331       g_object_unref (child->anchor);
9332     }
9333
9334   g_object_unref (child->widget);
9335
9336   g_free (child);
9337 }
9338
9339 static void
9340 text_view_child_set_parent_window (GtkTextView      *text_view,
9341                                    GtkTextViewChild *vc)
9342 {
9343   if (vc->anchor)
9344     gtk_widget_set_parent_window (vc->widget,
9345                                   text_view->priv->text_window->bin_window);
9346   else
9347     {
9348       GdkWindow *window;
9349       window = gtk_text_view_get_window (text_view,
9350                                          vc->type);
9351       gtk_widget_set_parent_window (vc->widget, window);
9352     }
9353 }
9354
9355 static void
9356 add_child (GtkTextView      *text_view,
9357            GtkTextViewChild *vc)
9358 {
9359   text_view->priv->children = g_slist_prepend (text_view->priv->children,
9360                                                vc);
9361
9362   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9363     text_view_child_set_parent_window (text_view, vc);
9364   
9365   gtk_widget_set_parent (vc->widget, GTK_WIDGET (text_view));
9366 }
9367
9368 /**
9369  * gtk_text_view_add_child_at_anchor:
9370  * @text_view: a #GtkTextView
9371  * @child: a #GtkWidget
9372  * @anchor: a #GtkTextChildAnchor in the #GtkTextBuffer for @text_view
9373  * 
9374  * Adds a child widget in the text buffer, at the given @anchor.
9375  **/
9376 void
9377 gtk_text_view_add_child_at_anchor (GtkTextView          *text_view,
9378                                    GtkWidget            *child,
9379                                    GtkTextChildAnchor   *anchor)
9380 {
9381   GtkTextViewChild *vc;
9382
9383   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9384   g_return_if_fail (GTK_IS_WIDGET (child));
9385   g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
9386   g_return_if_fail (gtk_widget_get_parent (child) == NULL);
9387
9388   gtk_text_view_ensure_layout (text_view);
9389
9390   vc = text_view_child_new_anchored (child, anchor,
9391                                      text_view->priv->layout);
9392
9393   add_child (text_view, vc);
9394
9395   g_assert (vc->widget == child);
9396   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9397 }
9398
9399 /**
9400  * gtk_text_view_add_child_in_window:
9401  * @text_view: a #GtkTextView
9402  * @child: a #GtkWidget
9403  * @which_window: which window the child should appear in
9404  * @xpos: X position of child in window coordinates
9405  * @ypos: Y position of child in window coordinates
9406  *
9407  * Adds a child at fixed coordinates in one of the text widget's
9408  * windows.
9409  *
9410  * The window must have nonzero size (see
9411  * gtk_text_view_set_border_window_size()). Note that the child
9412  * coordinates are given relative to the #GdkWindow in question, and
9413  * that these coordinates have no sane relationship to scrolling. When
9414  * placing a child in #GTK_TEXT_WINDOW_WIDGET, scrolling is
9415  * irrelevant, the child floats above all scrollable areas. But when
9416  * placing a child in one of the scrollable windows (border windows or
9417  * text window), you'll need to compute the child's correct position
9418  * in buffer coordinates any time scrolling occurs or buffer changes
9419  * occur, and then call gtk_text_view_move_child() to update the
9420  * child's position.
9421  */
9422 void
9423 gtk_text_view_add_child_in_window (GtkTextView       *text_view,
9424                                    GtkWidget         *child,
9425                                    GtkTextWindowType  which_window,
9426                                    gint               xpos,
9427                                    gint               ypos)
9428 {
9429   GtkTextViewChild *vc;
9430
9431   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9432   g_return_if_fail (GTK_IS_WIDGET (child));
9433   g_return_if_fail (gtk_widget_get_parent (child) == NULL);
9434
9435   vc = text_view_child_new_window (child, which_window,
9436                                    xpos, ypos);
9437
9438   add_child (text_view, vc);
9439
9440   g_assert (vc->widget == child);
9441   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9442 }
9443
9444 /**
9445  * gtk_text_view_move_child:
9446  * @text_view: a #GtkTextView
9447  * @child: child widget already added to the text view
9448  * @xpos: new X position in window coordinates
9449  * @ypos: new Y position in window coordinates
9450  *
9451  * Updates the position of a child, as for gtk_text_view_add_child_in_window().
9452  **/
9453 void
9454 gtk_text_view_move_child (GtkTextView *text_view,
9455                           GtkWidget   *child,
9456                           gint         xpos,
9457                           gint         ypos)
9458 {
9459   GtkTextViewChild *vc;
9460
9461   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9462   g_return_if_fail (GTK_IS_WIDGET (child));
9463   g_return_if_fail (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9464
9465   vc = g_object_get_data (G_OBJECT (child),
9466                           "gtk-text-view-child");
9467
9468   g_assert (vc != NULL);
9469
9470   if (vc->x == xpos &&
9471       vc->y == ypos)
9472     return;
9473   
9474   vc->x = xpos;
9475   vc->y = ypos;
9476
9477   if (gtk_widget_get_visible (child) &&
9478       gtk_widget_get_visible (GTK_WIDGET (text_view)))
9479     gtk_widget_queue_resize (child);
9480 }
9481
9482
9483 /* Iterator operations */
9484
9485 /**
9486  * gtk_text_view_forward_display_line:
9487  * @text_view: a #GtkTextView
9488  * @iter: a #GtkTextIter
9489  * 
9490  * Moves the given @iter forward by one display (wrapped) line.
9491  * A display line is different from a paragraph. Paragraphs are
9492  * separated by newlines or other paragraph separator characters.
9493  * Display lines are created by line-wrapping a paragraph. If
9494  * wrapping is turned off, display lines and paragraphs will be the
9495  * same. Display lines are divided differently for each view, since
9496  * they depend on the view's width; paragraphs are the same in all
9497  * views, since they depend on the contents of the #GtkTextBuffer.
9498  * 
9499  * Return value: %TRUE if @iter was moved and is not on the end iterator
9500  **/
9501 gboolean
9502 gtk_text_view_forward_display_line (GtkTextView *text_view,
9503                                     GtkTextIter *iter)
9504 {
9505   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9506   g_return_val_if_fail (iter != NULL, FALSE);
9507
9508   gtk_text_view_ensure_layout (text_view);
9509
9510   return gtk_text_layout_move_iter_to_next_line (text_view->priv->layout, iter);
9511 }
9512
9513 /**
9514  * gtk_text_view_backward_display_line:
9515  * @text_view: a #GtkTextView
9516  * @iter: a #GtkTextIter
9517  * 
9518  * Moves the given @iter backward by one display (wrapped) line.
9519  * A display line is different from a paragraph. Paragraphs are
9520  * separated by newlines or other paragraph separator characters.
9521  * Display lines are created by line-wrapping a paragraph. If
9522  * wrapping is turned off, display lines and paragraphs will be the
9523  * same. Display lines are divided differently for each view, since
9524  * they depend on the view's width; paragraphs are the same in all
9525  * views, since they depend on the contents of the #GtkTextBuffer.
9526  * 
9527  * Return value: %TRUE if @iter was moved and is not on the end iterator
9528  **/
9529 gboolean
9530 gtk_text_view_backward_display_line (GtkTextView *text_view,
9531                                      GtkTextIter *iter)
9532 {
9533   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9534   g_return_val_if_fail (iter != NULL, FALSE);
9535
9536   gtk_text_view_ensure_layout (text_view);
9537
9538   return gtk_text_layout_move_iter_to_previous_line (text_view->priv->layout, iter);
9539 }
9540
9541 /**
9542  * gtk_text_view_forward_display_line_end:
9543  * @text_view: a #GtkTextView
9544  * @iter: a #GtkTextIter
9545  * 
9546  * Moves the given @iter forward to the next display line end.
9547  * A display line is different from a paragraph. Paragraphs are
9548  * separated by newlines or other paragraph separator characters.
9549  * Display lines are created by line-wrapping a paragraph. If
9550  * wrapping is turned off, display lines and paragraphs will be the
9551  * same. Display lines are divided differently for each view, since
9552  * they depend on the view's width; paragraphs are the same in all
9553  * views, since they depend on the contents of the #GtkTextBuffer.
9554  * 
9555  * Return value: %TRUE if @iter was moved and is not on the end iterator
9556  **/
9557 gboolean
9558 gtk_text_view_forward_display_line_end (GtkTextView *text_view,
9559                                         GtkTextIter *iter)
9560 {
9561   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9562   g_return_val_if_fail (iter != NULL, FALSE);
9563
9564   gtk_text_view_ensure_layout (text_view);
9565
9566   return gtk_text_layout_move_iter_to_line_end (text_view->priv->layout, iter, 1);
9567 }
9568
9569 /**
9570  * gtk_text_view_backward_display_line_start:
9571  * @text_view: a #GtkTextView
9572  * @iter: a #GtkTextIter
9573  * 
9574  * Moves the given @iter backward to the next display line start.
9575  * A display line is different from a paragraph. Paragraphs are
9576  * separated by newlines or other paragraph separator characters.
9577  * Display lines are created by line-wrapping a paragraph. If
9578  * wrapping is turned off, display lines and paragraphs will be the
9579  * same. Display lines are divided differently for each view, since
9580  * they depend on the view's width; paragraphs are the same in all
9581  * views, since they depend on the contents of the #GtkTextBuffer.
9582  * 
9583  * Return value: %TRUE if @iter was moved and is not on the end iterator
9584  **/
9585 gboolean
9586 gtk_text_view_backward_display_line_start (GtkTextView *text_view,
9587                                            GtkTextIter *iter)
9588 {
9589   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9590   g_return_val_if_fail (iter != NULL, FALSE);
9591
9592   gtk_text_view_ensure_layout (text_view);
9593
9594   return gtk_text_layout_move_iter_to_line_end (text_view->priv->layout, iter, -1);
9595 }
9596
9597 /**
9598  * gtk_text_view_starts_display_line:
9599  * @text_view: a #GtkTextView
9600  * @iter: a #GtkTextIter
9601  * 
9602  * Determines whether @iter is at the start of a display line.
9603  * See gtk_text_view_forward_display_line() for an explanation of
9604  * display lines vs. paragraphs.
9605  * 
9606  * Return value: %TRUE if @iter begins a wrapped line
9607  **/
9608 gboolean
9609 gtk_text_view_starts_display_line (GtkTextView       *text_view,
9610                                    const GtkTextIter *iter)
9611 {
9612   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9613   g_return_val_if_fail (iter != NULL, FALSE);
9614
9615   gtk_text_view_ensure_layout (text_view);
9616
9617   return gtk_text_layout_iter_starts_line (text_view->priv->layout, iter);
9618 }
9619
9620 /**
9621  * gtk_text_view_move_visually:
9622  * @text_view: a #GtkTextView
9623  * @iter: a #GtkTextIter
9624  * @count: number of characters to move (negative moves left, 
9625  *    positive moves right)
9626  *
9627  * Move the iterator a given number of characters visually, treating
9628  * it as the strong cursor position. If @count is positive, then the
9629  * new strong cursor position will be @count positions to the right of
9630  * the old cursor position. If @count is negative then the new strong
9631  * cursor position will be @count positions to the left of the old
9632  * cursor position.
9633  *
9634  * In the presence of bi-directional text, the correspondence
9635  * between logical and visual order will depend on the direction
9636  * of the current run, and there may be jumps when the cursor
9637  * is moved off of the end of a run.
9638  * 
9639  * Return value: %TRUE if @iter moved and is not on the end iterator
9640  **/
9641 gboolean
9642 gtk_text_view_move_visually (GtkTextView *text_view,
9643                              GtkTextIter *iter,
9644                              gint         count)
9645 {
9646   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9647   g_return_val_if_fail (iter != NULL, FALSE);
9648
9649   gtk_text_view_ensure_layout (text_view);
9650
9651   return gtk_text_layout_move_iter_visually (text_view->priv->layout, iter, count);
9652 }