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