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