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