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