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