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