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