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