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