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