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