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