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