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