]> Pileus Git - ~andy/gtk/blob - gtk/gtktextview.c
gtk/gtkadjustment.c gtk/gtkclist.c gtk/gtkcolorsel.c gtk/gtkiconview.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 &&
4099            GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_press_event (widget, event))
4100     retval = TRUE;
4101   /* use overall editability not can_insert, more predictable for users */
4102   else if (text_view->editable &&
4103            (event->keyval == GDK_Return ||
4104             event->keyval == GDK_ISO_Enter ||
4105             event->keyval == GDK_KP_Enter))
4106     {
4107       /* this won't actually insert the newline if the cursor isn't
4108        * editable
4109        */
4110       gtk_text_view_reset_im_context (text_view);
4111       gtk_text_view_commit_text (text_view, "\n");
4112
4113       obscure = TRUE;
4114       retval = TRUE;
4115     }
4116   /* Pass through Tab as literal tab, unless Control is held down */
4117   else if ((event->keyval == GDK_Tab ||
4118             event->keyval == GDK_KP_Tab ||
4119             event->keyval == GDK_ISO_Left_Tab) &&
4120            !(event->state & GDK_CONTROL_MASK))
4121     {
4122       /* If the text widget isn't editable overall, or if the application
4123        * has turned off "accepts_tab", move the focus instead
4124        */
4125       if (text_view->accepts_tab && text_view->editable)
4126         {
4127           gtk_text_view_reset_im_context (text_view);
4128           gtk_text_view_commit_text (text_view, "\t");
4129           obscure = TRUE;
4130         }
4131       else
4132         g_signal_emit_by_name (text_view, "move-focus",
4133                                (event->state & GDK_SHIFT_MASK) ?
4134                                GTK_DIR_TAB_BACKWARD : GTK_DIR_TAB_FORWARD);
4135
4136       retval = TRUE;
4137     }
4138   else
4139     retval = FALSE;
4140
4141   if (obscure)
4142     gtk_text_view_obscure_mouse_cursor (text_view);
4143   
4144   gtk_text_view_reset_blink_time (text_view);
4145   gtk_text_view_pend_cursor_blink (text_view);
4146
4147   return retval;
4148 }
4149
4150 static gint
4151 gtk_text_view_key_release_event (GtkWidget *widget, GdkEventKey *event)
4152 {
4153   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4154   GtkTextMark *insert;
4155   GtkTextIter iter;
4156
4157   if (text_view->layout == NULL || get_buffer (text_view) == NULL)
4158     return FALSE;
4159       
4160   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4161   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4162   if (gtk_text_iter_can_insert (&iter, text_view->editable) &&
4163       gtk_im_context_filter_keypress (text_view->im_context, event))
4164     {
4165       text_view->need_im_reset = TRUE;
4166       return TRUE;
4167     }
4168   else
4169     return GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_release_event (widget, event);
4170 }
4171
4172 static gint
4173 gtk_text_view_button_press_event (GtkWidget *widget, GdkEventButton *event)
4174 {
4175   GtkTextView *text_view;
4176
4177   text_view = GTK_TEXT_VIEW (widget);
4178
4179   gtk_widget_grab_focus (widget);
4180
4181   if (event->window != text_view->text_window->bin_window)
4182     {
4183       /* Remove selection if any. */
4184       gtk_text_view_unselect (text_view);
4185       return FALSE;
4186     }
4187
4188   gtk_text_view_reset_blink_time (text_view);
4189
4190 #if 0
4191   /* debug hack */
4192   if (event->button == 3 && (event->state & GDK_CONTROL_MASK) != 0)
4193     _gtk_text_buffer_spew (GTK_TEXT_VIEW (widget)->buffer);
4194   else if (event->button == 3)
4195     gtk_text_layout_spew (GTK_TEXT_VIEW (widget)->layout);
4196 #endif
4197
4198   if (event->type == GDK_BUTTON_PRESS)
4199     {
4200       gtk_text_view_reset_im_context (text_view);
4201
4202       if (event->button == 1)
4203         {
4204           /* If we're in the selection, start a drag copy/move of the
4205            * selection; otherwise, start creating a new selection.
4206            */
4207           GtkTextIter iter;
4208           GtkTextIter start, end;
4209
4210           gtk_text_layout_get_iter_at_pixel (text_view->layout,
4211                                              &iter,
4212                                              event->x + text_view->xoffset,
4213                                              event->y + text_view->yoffset);
4214
4215           if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
4216                                                     &start, &end) &&
4217               gtk_text_iter_in_range (&iter, &start, &end))
4218             {
4219               text_view->drag_start_x = event->x;
4220               text_view->drag_start_y = event->y;
4221               text_view->pending_place_cursor_button = event->button;
4222             }
4223           else
4224             {
4225               gtk_text_view_start_selection_drag (text_view, &iter, event);
4226             }
4227
4228           return TRUE;
4229         }
4230       else if (event->button == 2)
4231         {
4232           GtkTextIter iter;
4233
4234           gtk_text_layout_get_iter_at_pixel (text_view->layout,
4235                                              &iter,
4236                                              event->x + text_view->xoffset,
4237                                              event->y + text_view->yoffset);
4238
4239           gtk_text_buffer_paste_clipboard (get_buffer (text_view),
4240                                            gtk_widget_get_clipboard (widget, GDK_SELECTION_PRIMARY),
4241                                            &iter,
4242                                            text_view->editable);
4243           return TRUE;
4244         }
4245       else if (event->button == 3)
4246         {
4247           gtk_text_view_do_popup (text_view, event);
4248           return TRUE;
4249         }
4250     }
4251   else if ((event->type == GDK_2BUTTON_PRESS ||
4252             event->type == GDK_3BUTTON_PRESS) &&
4253            event->button == 1) 
4254     {
4255       GtkTextIter iter;
4256
4257       gtk_text_view_end_selection_drag (text_view);
4258
4259       gtk_text_layout_get_iter_at_pixel (text_view->layout,
4260                                          &iter,
4261                                          event->x + text_view->xoffset,
4262                                          event->y + text_view->yoffset);
4263       
4264       gtk_text_view_start_selection_drag (text_view, &iter, event);
4265       return TRUE;
4266     }
4267   
4268   return FALSE;
4269 }
4270
4271 static gint
4272 gtk_text_view_button_release_event (GtkWidget *widget, GdkEventButton *event)
4273 {
4274   GtkTextView *text_view;
4275
4276   text_view = GTK_TEXT_VIEW (widget);
4277
4278   if (event->window != text_view->text_window->bin_window)
4279     return FALSE;
4280
4281   if (event->button == 1)
4282     {
4283       if (text_view->drag_start_x >= 0)
4284         {
4285           text_view->drag_start_x = -1;
4286           text_view->drag_start_y = -1;
4287         }
4288
4289       if (gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget)))
4290         return TRUE;
4291       else if (text_view->pending_place_cursor_button == event->button)
4292         {
4293           GtkTextIter iter;
4294
4295           /* Unselect everything; we clicked inside selection, but
4296            * didn't move by the drag threshold, so just clear selection
4297            * and place cursor.
4298            */
4299           gtk_text_layout_get_iter_at_pixel (text_view->layout,
4300                                              &iter,
4301                                              event->x + text_view->xoffset,
4302                                              event->y + text_view->yoffset);
4303
4304           gtk_text_buffer_place_cursor (get_buffer (text_view), &iter);
4305           gtk_text_view_check_cursor_blink (text_view);
4306           
4307           text_view->pending_place_cursor_button = 0;
4308           
4309           return FALSE;
4310         }
4311     }
4312
4313   return FALSE;
4314 }
4315
4316 static void
4317 keymap_direction_changed (GdkKeymap   *keymap,
4318                           GtkTextView *text_view)
4319 {
4320   gtk_text_view_check_keymap_direction (text_view);
4321 }
4322
4323 static gint
4324 gtk_text_view_focus_in_event (GtkWidget *widget, GdkEventFocus *event)
4325 {
4326   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4327
4328   gtk_widget_queue_draw (widget);
4329
4330   DV(g_print (G_STRLOC": focus_in_event\n"));
4331
4332   gtk_text_view_reset_blink_time (text_view);
4333
4334   if (text_view->cursor_visible && text_view->layout)
4335     {
4336       gtk_text_layout_set_cursor_visible (text_view->layout, TRUE);
4337       gtk_text_view_check_cursor_blink (text_view);
4338     }
4339
4340   g_signal_connect (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
4341                     "direction_changed",
4342                     G_CALLBACK (keymap_direction_changed), text_view);
4343   gtk_text_view_check_keymap_direction (text_view);
4344
4345   if (text_view->editable)
4346     {
4347       text_view->need_im_reset = TRUE;
4348       gtk_im_context_focus_in (GTK_TEXT_VIEW (widget)->im_context);
4349     }
4350
4351   return FALSE;
4352 }
4353
4354 static gint
4355 gtk_text_view_focus_out_event (GtkWidget *widget, GdkEventFocus *event)
4356 {
4357   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4358
4359   gtk_text_view_end_selection_drag (text_view);
4360
4361   gtk_widget_queue_draw (widget);
4362
4363   DV(g_print (G_STRLOC": focus_out_event\n"));
4364   
4365   if (text_view->cursor_visible && text_view->layout)
4366     {
4367       gtk_text_view_check_cursor_blink (text_view);
4368       gtk_text_layout_set_cursor_visible (text_view->layout, FALSE);
4369     }
4370
4371   g_signal_handlers_disconnect_by_func (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
4372                                         keymap_direction_changed,
4373                                         text_view);
4374
4375   if (text_view->editable)
4376     {
4377       text_view->need_im_reset = TRUE;
4378       gtk_im_context_focus_out (GTK_TEXT_VIEW (widget)->im_context);
4379     }
4380
4381   return FALSE;
4382 }
4383
4384 static gint
4385 gtk_text_view_motion_event (GtkWidget *widget, GdkEventMotion *event)
4386 {
4387   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4388
4389   gtk_text_view_unobscure_mouse_cursor (text_view);
4390
4391   if (event->window == text_view->text_window->bin_window &&
4392       text_view->drag_start_x >= 0)
4393     {
4394       gint x = event->x;
4395       gint y = event->y;
4396
4397       gdk_event_request_motions (event);
4398
4399       if (gtk_drag_check_threshold (widget,
4400                                     text_view->drag_start_x, 
4401                                     text_view->drag_start_y,
4402                                     x, y))
4403         {
4404           GtkTextIter iter;
4405           gint buffer_x, buffer_y;
4406
4407           gtk_text_view_window_to_buffer_coords (text_view,
4408                                                  GTK_TEXT_WINDOW_TEXT,
4409                                                  text_view->drag_start_x,
4410                                                  text_view->drag_start_y,
4411                                                  &buffer_x,
4412                                                  &buffer_y);
4413
4414           gtk_text_layout_get_iter_at_pixel (text_view->layout,
4415                                              &iter,
4416                                              buffer_x, buffer_y);
4417
4418           gtk_text_view_start_selection_dnd (text_view, &iter, event);
4419           return TRUE;
4420         }
4421     }
4422
4423   return FALSE;
4424 }
4425
4426 static void
4427 gtk_text_view_paint (GtkWidget      *widget,
4428                      GdkRectangle   *area,
4429                      GdkEventExpose *event)
4430 {
4431   GtkTextView *text_view;
4432   GList *child_exposes;
4433   GList *tmp_list;
4434   GdkRegion *updates;
4435   
4436   text_view = GTK_TEXT_VIEW (widget);
4437
4438   g_return_if_fail (text_view->layout != NULL);
4439   g_return_if_fail (text_view->xoffset >= 0);
4440   g_return_if_fail (text_view->yoffset >= 0);
4441
4442   while (text_view->first_validate_idle != 0)
4443     {
4444       DV (g_print (G_STRLOC": first_validate_idle: %d\n",
4445                    text_view->first_validate_idle));
4446       gtk_text_view_flush_first_validate (text_view);
4447     }
4448
4449   /* More regions could have become invalid in the above loop */
4450   updates = gdk_window_get_update_area (text_view->text_window->bin_window);
4451   if (updates)
4452     {
4453       GdkRectangle rect;
4454       
4455       gdk_region_get_clipbox (updates, &rect);
4456
4457       gdk_rectangle_union (area, &rect, area);
4458       
4459       gdk_region_destroy (updates);
4460     }
4461   
4462   if (!text_view->onscreen_validated)
4463     {
4464       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.");
4465       g_assert_not_reached ();
4466     }
4467   
4468 #if 0
4469   printf ("painting %d,%d  %d x %d\n",
4470           area->x, area->y,
4471           area->width, area->height);
4472 #endif
4473
4474   child_exposes = NULL;
4475   gtk_text_layout_draw (text_view->layout,
4476                         widget,
4477                         text_view->text_window->bin_window,
4478                         NULL,
4479                         text_view->xoffset,
4480                         text_view->yoffset,
4481                         area->x, area->y,
4482                         area->width, area->height,
4483                         &child_exposes);
4484
4485   tmp_list = child_exposes;
4486   while (tmp_list != NULL)
4487     {
4488       GtkWidget *child = tmp_list->data;
4489   
4490       gtk_container_propagate_expose (GTK_CONTAINER (text_view),
4491                                       child,
4492                                       event);
4493
4494       g_object_unref (child);
4495       
4496       tmp_list = tmp_list->next;
4497     }
4498
4499   g_list_free (child_exposes);
4500 }
4501
4502 static gint
4503 gtk_text_view_expose_event (GtkWidget *widget, GdkEventExpose *event)
4504 {
4505   GSList *tmp_list;
4506   
4507   if (event->window == gtk_text_view_get_window (GTK_TEXT_VIEW (widget),
4508                                                  GTK_TEXT_WINDOW_TEXT))
4509     {
4510       DV(g_print (">Exposed ("G_STRLOC")\n"));
4511       gtk_text_view_paint (widget, &event->area, event);
4512     }
4513
4514   if (event->window == widget->window)
4515     gtk_text_view_draw_focus (widget);
4516
4517   /* Propagate exposes to all unanchored children. 
4518    * Anchored children are handled in gtk_text_view_paint(). 
4519    */
4520   tmp_list = GTK_TEXT_VIEW (widget)->children;
4521   while (tmp_list != NULL)
4522     {
4523       GtkTextViewChild *vc = tmp_list->data;
4524
4525       /* propagate_expose checks that event->window matches
4526        * child->window
4527        */
4528       if (!vc->anchor)
4529         gtk_container_propagate_expose (GTK_CONTAINER (widget),
4530                                         vc->widget,
4531                                         event);
4532       
4533       tmp_list = tmp_list->next;
4534     }
4535   
4536   return FALSE;
4537 }
4538
4539 static void
4540 gtk_text_view_draw_focus (GtkWidget *widget)
4541 {
4542   gboolean interior_focus;
4543
4544   /* We clear the focus if we are in interior focus mode. */
4545   gtk_widget_style_get (widget,
4546                         "interior-focus", &interior_focus,
4547                         NULL);
4548   
4549   if (GTK_WIDGET_DRAWABLE (widget))
4550     {
4551       if (GTK_WIDGET_HAS_FOCUS (widget) && !interior_focus)
4552         {          
4553           gtk_paint_focus (widget->style, widget->window, GTK_WIDGET_STATE (widget), 
4554                            NULL, widget, "textview",
4555                            0, 0,
4556                            widget->allocation.width,
4557                            widget->allocation.height);
4558         }
4559       else
4560         {
4561           gdk_window_clear (widget->window);
4562         }
4563     }
4564 }
4565
4566 static gboolean
4567 gtk_text_view_focus (GtkWidget        *widget,
4568                      GtkDirectionType  direction)
4569 {
4570   GtkContainer *container;
4571   gboolean result;
4572   
4573   container = GTK_CONTAINER (widget);  
4574
4575   if (!gtk_widget_is_focus (widget) &&
4576       container->focus_child == NULL)
4577     {
4578       gtk_widget_grab_focus (widget);
4579       return TRUE;
4580     }
4581   else
4582     {
4583       /*
4584        * Unset CAN_FOCUS flag so that gtk_container_focus() allows
4585        * children to get the focus
4586        */
4587       GTK_WIDGET_UNSET_FLAGS (widget, GTK_CAN_FOCUS); 
4588       result = GTK_WIDGET_CLASS (gtk_text_view_parent_class)->focus (widget, direction);
4589       GTK_WIDGET_SET_FLAGS (widget, GTK_CAN_FOCUS); 
4590
4591       return result;
4592     }
4593 }
4594
4595 static void
4596 gtk_text_view_move_focus (GtkWidget        *widget,
4597                           GtkDirectionType  direction_type)
4598 {
4599   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4600
4601   if (GTK_TEXT_VIEW_GET_CLASS (text_view)->move_focus)
4602     GTK_TEXT_VIEW_GET_CLASS (text_view)->move_focus (text_view,
4603                                                      direction_type);
4604 }
4605
4606 /*
4607  * Container
4608  */
4609
4610 static void
4611 gtk_text_view_add (GtkContainer *container,
4612                    GtkWidget    *child)
4613 {
4614   /* This is pretty random. */
4615   gtk_text_view_add_child_in_window (GTK_TEXT_VIEW (container),
4616                                      child,
4617                                      GTK_TEXT_WINDOW_WIDGET,
4618                                      0, 0);
4619 }
4620
4621 static void
4622 gtk_text_view_remove (GtkContainer *container,
4623                       GtkWidget    *child)
4624 {
4625   GSList *iter;
4626   GtkTextView *text_view;
4627   GtkTextViewChild *vc;
4628
4629   text_view = GTK_TEXT_VIEW (container);
4630
4631   vc = NULL;
4632   iter = text_view->children;
4633
4634   while (iter != NULL)
4635     {
4636       vc = iter->data;
4637
4638       if (vc->widget == child)
4639         break;
4640
4641       iter = g_slist_next (iter);
4642     }
4643
4644   g_assert (iter != NULL); /* be sure we had the child in the list */
4645
4646   text_view->children = g_slist_remove (text_view->children, vc);
4647
4648   gtk_widget_unparent (vc->widget);
4649
4650   text_view_child_free (vc);
4651 }
4652
4653 static void
4654 gtk_text_view_forall (GtkContainer *container,
4655                       gboolean      include_internals,
4656                       GtkCallback   callback,
4657                       gpointer      callback_data)
4658 {
4659   GSList *iter;
4660   GtkTextView *text_view;
4661   GSList *copy;
4662
4663   g_return_if_fail (GTK_IS_TEXT_VIEW (container));
4664   g_return_if_fail (callback != NULL);
4665
4666   text_view = GTK_TEXT_VIEW (container);
4667
4668   copy = g_slist_copy (text_view->children);
4669   iter = copy;
4670
4671   while (iter != NULL)
4672     {
4673       GtkTextViewChild *vc = iter->data;
4674
4675       (* callback) (vc->widget, callback_data);
4676
4677       iter = g_slist_next (iter);
4678     }
4679
4680   g_slist_free (copy);
4681 }
4682
4683 #define CURSOR_ON_MULTIPLIER 2
4684 #define CURSOR_OFF_MULTIPLIER 1
4685 #define CURSOR_PEND_MULTIPLIER 3
4686 #define CURSOR_DIVIDER 3
4687
4688 static gboolean
4689 cursor_blinks (GtkTextView *text_view)
4690 {
4691   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
4692   gboolean blink;
4693
4694 #ifdef DEBUG_VALIDATION_AND_SCROLLING
4695   return FALSE;
4696 #endif
4697   if (gtk_debug_flags & GTK_DEBUG_UPDATES)
4698     return FALSE;
4699
4700   g_object_get (settings, "gtk-cursor-blink", &blink, NULL);
4701
4702   if (!blink)
4703     return FALSE;
4704
4705   if (text_view->editable)
4706     {
4707       GtkTextMark *insert;
4708       GtkTextIter iter;
4709       
4710       insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4711       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4712       
4713       if (gtk_text_iter_editable (&iter, text_view->editable))
4714         return blink;
4715     }
4716
4717   return FALSE;
4718 }
4719
4720 static gint
4721 get_cursor_time (GtkTextView *text_view)
4722 {
4723   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
4724   gint time;
4725
4726   g_object_get (settings, "gtk-cursor-blink-time", &time, NULL);
4727
4728   return time;
4729 }
4730
4731 static gint
4732 get_cursor_blink_timeout (GtkTextView *text_view)
4733 {
4734   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
4735   gint time;
4736
4737   g_object_get (settings, "gtk-cursor-blink-timeout", &time, NULL);
4738
4739   return time;
4740 }
4741
4742
4743 /*
4744  * Blink!
4745  */
4746
4747 static gint
4748 blink_cb (gpointer data)
4749 {
4750   GtkTextView *text_view;
4751   GtkTextViewPrivate *priv;
4752   gboolean visible;
4753   gint blink_timeout;
4754
4755   text_view = GTK_TEXT_VIEW (data);
4756   priv = GTK_TEXT_VIEW_GET_PRIVATE (text_view);
4757
4758   if (!GTK_WIDGET_HAS_FOCUS (text_view))
4759     {
4760       g_warning ("GtkTextView - did not receive focus-out-event. If you\n"
4761                  "connect a handler to this signal, it must return\n"
4762                  "FALSE so the text view gets the event as well");
4763
4764       gtk_text_view_check_cursor_blink (text_view);
4765
4766       return FALSE;
4767     }
4768
4769   g_assert (text_view->layout);
4770   g_assert (text_view->cursor_visible);
4771
4772   visible = gtk_text_layout_get_cursor_visible (text_view->layout);
4773
4774   blink_timeout = get_cursor_blink_timeout (text_view);
4775   if (priv->blink_time > 1000 * blink_timeout &&
4776       blink_timeout < G_MAXINT/1000) 
4777     {
4778       /* we've blinked enough without the user doing anything, stop blinking */
4779       visible = 0;
4780       text_view->blink_timeout = 0;
4781     } 
4782   else if (visible)
4783     text_view->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER / CURSOR_DIVIDER,
4784                                               blink_cb,
4785                                               text_view);
4786   else 
4787     {
4788       text_view->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_ON_MULTIPLIER / CURSOR_DIVIDER,
4789                                                 blink_cb,
4790                                                 text_view);
4791       priv->blink_time += get_cursor_time (text_view);
4792     }
4793
4794   /* Block changed_handler while changing the layout's cursor visibility
4795    * because it would expose the whole paragraph. Instead, we expose
4796    * the cursor's area(s) manually below.
4797    */
4798   g_signal_handlers_block_by_func (text_view->layout,
4799                                    changed_handler,
4800                                    text_view);
4801   gtk_text_layout_set_cursor_visible (text_view->layout, !visible);
4802   g_signal_handlers_unblock_by_func (text_view->layout,
4803                                      changed_handler,
4804                                      text_view);
4805
4806   text_window_invalidate_cursors (text_view->text_window);
4807
4808   /* Remove ourselves */
4809   return FALSE;
4810 }
4811
4812
4813 static void
4814 gtk_text_view_stop_cursor_blink (GtkTextView *text_view)
4815 {
4816   if (text_view->blink_timeout)  
4817     { 
4818       g_source_remove (text_view->blink_timeout);
4819       text_view->blink_timeout = 0;
4820     }
4821 }
4822
4823 static void
4824 gtk_text_view_check_cursor_blink (GtkTextView *text_view)
4825 {
4826   if (text_view->layout != NULL &&
4827       text_view->cursor_visible &&
4828       GTK_WIDGET_HAS_FOCUS (text_view))
4829     {
4830       if (cursor_blinks (text_view))
4831         {
4832           if (text_view->blink_timeout == 0)
4833             {
4834               gtk_text_layout_set_cursor_visible (text_view->layout, TRUE);
4835               
4836               text_view->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER / CURSOR_DIVIDER,
4837                                                         blink_cb,
4838                                                         text_view);
4839             }
4840         }
4841       else
4842         {
4843           gtk_text_view_stop_cursor_blink (text_view);
4844           gtk_text_layout_set_cursor_visible (text_view->layout, TRUE);
4845         }
4846     }
4847   else
4848     {
4849       gtk_text_view_stop_cursor_blink (text_view);
4850       gtk_text_layout_set_cursor_visible (text_view->layout, FALSE);
4851     }
4852 }
4853
4854 static void
4855 gtk_text_view_pend_cursor_blink (GtkTextView *text_view)
4856 {
4857   if (text_view->layout != NULL &&
4858       text_view->cursor_visible &&
4859       GTK_WIDGET_HAS_FOCUS (text_view) &&
4860       cursor_blinks (text_view))
4861     {
4862       gtk_text_view_stop_cursor_blink (text_view);
4863       gtk_text_layout_set_cursor_visible (text_view->layout, TRUE);
4864       
4865       text_view->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_PEND_MULTIPLIER / CURSOR_DIVIDER,
4866                                                 blink_cb,
4867                                                 text_view);
4868     }
4869 }
4870
4871 static void
4872 gtk_text_view_reset_blink_time (GtkTextView *text_view)
4873 {
4874   GtkTextViewPrivate *priv;
4875
4876   priv = GTK_TEXT_VIEW_GET_PRIVATE (text_view);
4877
4878   priv->blink_time = 0;
4879 }
4880
4881
4882 /*
4883  * Key binding handlers
4884  */
4885
4886 static gboolean
4887 gtk_text_view_move_iter_by_lines (GtkTextView *text_view,
4888                                   GtkTextIter *newplace,
4889                                   gint         count)
4890 {
4891   gboolean ret = TRUE;
4892
4893   while (count < 0)
4894     {
4895       ret = gtk_text_layout_move_iter_to_previous_line (text_view->layout, newplace);
4896       count++;
4897     }
4898
4899   while (count > 0)
4900     {
4901       ret = gtk_text_layout_move_iter_to_next_line (text_view->layout, newplace);
4902       count--;
4903     }
4904
4905   return ret;
4906 }
4907
4908 static void
4909 move_cursor (GtkTextView       *text_view,
4910              const GtkTextIter *new_location,
4911              gboolean           extend_selection)
4912 {
4913   if (extend_selection)
4914     gtk_text_buffer_move_mark_by_name (get_buffer (text_view),
4915                                        "insert",
4916                                        new_location);
4917   else
4918       gtk_text_buffer_place_cursor (get_buffer (text_view),
4919                                     new_location);
4920   gtk_text_view_check_cursor_blink (text_view);
4921 }
4922
4923 static void
4924 gtk_text_view_move_cursor_internal (GtkTextView     *text_view,
4925                                     GtkMovementStep  step,
4926                                     gint             count,
4927                                     gboolean         extend_selection)
4928 {
4929   GtkTextIter insert;
4930   GtkTextIter newplace;
4931   gint cursor_x_pos = 0;
4932   GtkDirectionType leave_direction = -1;
4933
4934   if (!text_view->cursor_visible) 
4935     {
4936       GtkScrollStep scroll_step;
4937
4938       switch (step) 
4939         {
4940         case GTK_MOVEMENT_VISUAL_POSITIONS:
4941           leave_direction = count > 0 ? GTK_DIR_RIGHT : GTK_DIR_LEFT;
4942           /* fall through */
4943         case GTK_MOVEMENT_LOGICAL_POSITIONS:
4944         case GTK_MOVEMENT_WORDS:
4945           scroll_step = GTK_SCROLL_HORIZONTAL_STEPS;
4946           break;
4947         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
4948           scroll_step = GTK_SCROLL_HORIZONTAL_ENDS;
4949           break;          
4950         case GTK_MOVEMENT_DISPLAY_LINES:
4951           leave_direction = count > 0 ? GTK_DIR_DOWN : GTK_DIR_UP;
4952           /* fall through */
4953         case GTK_MOVEMENT_PARAGRAPHS:
4954         case GTK_MOVEMENT_PARAGRAPH_ENDS:
4955           scroll_step = GTK_SCROLL_STEPS;
4956           break;
4957         case GTK_MOVEMENT_PAGES:
4958           scroll_step = GTK_SCROLL_PAGES;
4959           break;
4960         case GTK_MOVEMENT_HORIZONTAL_PAGES:
4961           scroll_step = GTK_SCROLL_HORIZONTAL_PAGES;
4962           break;
4963         case GTK_MOVEMENT_BUFFER_ENDS:
4964           scroll_step = GTK_SCROLL_ENDS;
4965           break;
4966         default:
4967           scroll_step = GTK_SCROLL_PAGES;
4968           break;
4969         }
4970
4971       if (!gtk_text_view_move_viewport (text_view, scroll_step, count))
4972         {
4973           if (leave_direction != -1 &&
4974               !gtk_widget_keynav_failed (GTK_WIDGET (text_view),
4975                                          leave_direction))
4976             {
4977               g_signal_emit_by_name (text_view, "move-focus", leave_direction);
4978             }
4979         }
4980
4981       return;
4982     }
4983
4984   gtk_text_view_reset_im_context (text_view);
4985
4986   if (step == GTK_MOVEMENT_PAGES)
4987     {
4988       if (!gtk_text_view_scroll_pages (text_view, count, extend_selection))
4989         gtk_widget_error_bell (GTK_WIDGET (text_view));
4990
4991       gtk_text_view_check_cursor_blink (text_view);
4992       gtk_text_view_pend_cursor_blink (text_view);
4993       return;
4994     }
4995   else if (step == GTK_MOVEMENT_HORIZONTAL_PAGES)
4996     {
4997       if (!gtk_text_view_scroll_hpages (text_view, count, extend_selection))
4998         gtk_widget_error_bell (GTK_WIDGET (text_view));
4999
5000       gtk_text_view_check_cursor_blink (text_view);
5001       gtk_text_view_pend_cursor_blink (text_view);
5002       return;
5003     }
5004
5005   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5006                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5007   newplace = insert;
5008
5009   if (step == GTK_MOVEMENT_DISPLAY_LINES)
5010     gtk_text_view_get_virtual_cursor_pos (text_view, &cursor_x_pos, NULL);
5011
5012   switch (step)
5013     {
5014     case GTK_MOVEMENT_LOGICAL_POSITIONS:
5015       gtk_text_iter_forward_visible_cursor_positions (&newplace, count);
5016       break;
5017
5018     case GTK_MOVEMENT_VISUAL_POSITIONS:
5019       gtk_text_layout_move_iter_visually (text_view->layout,
5020                                           &newplace, count);
5021       break;
5022
5023     case GTK_MOVEMENT_WORDS:
5024       if (count < 0)
5025         gtk_text_iter_backward_visible_word_starts (&newplace, -count);
5026       else if (count > 0) 
5027         {
5028           if (!gtk_text_iter_forward_visible_word_ends (&newplace, count))
5029             gtk_text_iter_forward_to_line_end (&newplace);
5030         }
5031       break;
5032
5033     case GTK_MOVEMENT_DISPLAY_LINES:
5034       if (count < 0)
5035         {
5036           leave_direction = GTK_DIR_UP;
5037
5038           if (gtk_text_view_move_iter_by_lines (text_view, &newplace, count))
5039             gtk_text_layout_move_iter_to_x (text_view->layout, &newplace, cursor_x_pos);
5040           else
5041             gtk_text_iter_set_line_offset (&newplace, 0);
5042         }
5043       if (count > 0)
5044         {
5045           leave_direction = GTK_DIR_DOWN;
5046
5047           if (gtk_text_view_move_iter_by_lines (text_view, &newplace, count))
5048             gtk_text_layout_move_iter_to_x (text_view->layout, &newplace, cursor_x_pos);
5049           else
5050             gtk_text_iter_forward_to_line_end (&newplace);
5051         }
5052       break;
5053
5054     case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5055       if (count > 1)
5056         gtk_text_view_move_iter_by_lines (text_view, &newplace, --count);
5057       else if (count < -1)
5058         gtk_text_view_move_iter_by_lines (text_view, &newplace, ++count);
5059
5060       if (count != 0)
5061         gtk_text_layout_move_iter_to_line_end (text_view->layout, &newplace, count);
5062       break;
5063
5064     case GTK_MOVEMENT_PARAGRAPHS:
5065       if (count > 0)
5066         {
5067           if (!gtk_text_iter_ends_line (&newplace))
5068             {
5069               gtk_text_iter_forward_to_line_end (&newplace);
5070               --count;
5071             }
5072           gtk_text_iter_forward_visible_lines (&newplace, count);
5073           gtk_text_iter_forward_to_line_end (&newplace);
5074         }
5075       else if (count < 0)
5076         {
5077           if (gtk_text_iter_get_line_offset (&newplace) > 0)
5078             gtk_text_iter_set_line_offset (&newplace, 0);
5079           gtk_text_iter_forward_visible_lines (&newplace, count);
5080           gtk_text_iter_set_line_offset (&newplace, 0);
5081         }
5082       break;
5083
5084     case GTK_MOVEMENT_PARAGRAPH_ENDS:
5085       if (count > 0)
5086         {
5087           if (!gtk_text_iter_ends_line (&newplace))
5088             gtk_text_iter_forward_to_line_end (&newplace);
5089         }
5090       else if (count < 0)
5091         {
5092           gtk_text_iter_set_line_offset (&newplace, 0);
5093         }
5094       break;
5095
5096     case GTK_MOVEMENT_BUFFER_ENDS:
5097       if (count > 0)
5098         gtk_text_buffer_get_end_iter (get_buffer (text_view), &newplace);
5099       else if (count < 0)
5100         gtk_text_buffer_get_iter_at_offset (get_buffer (text_view), &newplace, 0);
5101      break;
5102       
5103     default:
5104       break;
5105     }
5106
5107   /* call move_cursor() even if the cursor hasn't moved, since it 
5108      cancels the selection
5109   */
5110   move_cursor (text_view, &newplace, extend_selection);
5111
5112   if (!gtk_text_iter_equal (&insert, &newplace))
5113     {
5114       DV(g_print (G_STRLOC": scrolling onscreen\n"));
5115       gtk_text_view_scroll_mark_onscreen (text_view,
5116                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
5117
5118       if (step == GTK_MOVEMENT_DISPLAY_LINES)
5119         gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, -1);
5120     }
5121   else if (leave_direction != -1)
5122     {
5123       if (!gtk_widget_keynav_failed (GTK_WIDGET (text_view),
5124                                      leave_direction))
5125         {
5126           g_signal_emit_by_name (text_view, "move-focus", leave_direction);
5127         }
5128     }
5129   else
5130     {
5131       gtk_widget_error_bell (GTK_WIDGET (text_view));
5132     }
5133
5134   gtk_text_view_check_cursor_blink (text_view);
5135   gtk_text_view_pend_cursor_blink (text_view);
5136 }
5137
5138 static void
5139 gtk_text_view_move_cursor (GtkTextView     *text_view,
5140                            GtkMovementStep  step,
5141                            gint             count,
5142                            gboolean         extend_selection)
5143 {
5144   gtk_text_view_move_cursor_internal (text_view, step, count, extend_selection);
5145 }
5146
5147 static void
5148 gtk_text_view_page_horizontally (GtkTextView     *text_view,
5149                                  gint             count,
5150                                  gboolean         extend_selection)
5151 {
5152   gtk_text_view_move_cursor_internal (text_view, GTK_MOVEMENT_HORIZONTAL_PAGES,
5153                                       count, extend_selection);
5154 }
5155
5156
5157 static gboolean
5158 gtk_text_view_move_viewport (GtkTextView     *text_view,
5159                              GtkScrollStep    step,
5160                              gint             count)
5161 {
5162   GtkAdjustment *adjustment;
5163   gdouble increment;
5164   
5165   switch (step) 
5166     {
5167     case GTK_SCROLL_STEPS:
5168     case GTK_SCROLL_PAGES:
5169     case GTK_SCROLL_ENDS:
5170       adjustment = get_vadjustment (text_view);
5171       break;
5172     case GTK_SCROLL_HORIZONTAL_STEPS:
5173     case GTK_SCROLL_HORIZONTAL_PAGES:
5174     case GTK_SCROLL_HORIZONTAL_ENDS:
5175       adjustment = get_hadjustment (text_view);
5176       break;
5177     default:
5178       adjustment = get_vadjustment (text_view);
5179       break;
5180     }
5181
5182   switch (step) 
5183     {
5184     case GTK_SCROLL_STEPS:
5185     case GTK_SCROLL_HORIZONTAL_STEPS:
5186       increment = adjustment->step_increment;
5187       break;
5188     case GTK_SCROLL_PAGES:
5189     case GTK_SCROLL_HORIZONTAL_PAGES:
5190       increment = adjustment->page_increment;
5191       break;
5192     case GTK_SCROLL_ENDS:
5193     case GTK_SCROLL_HORIZONTAL_ENDS:
5194       increment = adjustment->upper - adjustment->lower;
5195       break;
5196     default:
5197       increment = 0.0;
5198       break;
5199     }
5200
5201   return set_adjustment_clamped (adjustment, adjustment->value + count * increment);
5202 }
5203
5204 static void
5205 gtk_text_view_set_anchor (GtkTextView *text_view)
5206 {
5207   GtkTextIter insert;
5208
5209   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5210                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5211
5212   gtk_text_buffer_create_mark (get_buffer (text_view), "anchor", &insert, TRUE);
5213 }
5214
5215 static gboolean
5216 gtk_text_view_scroll_pages (GtkTextView *text_view,
5217                             gint         count,
5218                             gboolean     extend_selection)
5219 {
5220   gdouble newval;
5221   gdouble oldval;
5222   GtkAdjustment *adj;
5223   gint cursor_x_pos, cursor_y_pos;
5224   GtkTextMark *insert_mark;
5225   GtkTextIter old_insert;
5226   GtkTextIter new_insert;
5227   GtkTextIter anchor;
5228   gint y0, y1;
5229
5230   g_return_val_if_fail (text_view->vadjustment != NULL, FALSE);
5231   
5232   adj = text_view->vadjustment;
5233
5234   insert_mark = gtk_text_buffer_get_insert (get_buffer (text_view));
5235
5236   /* Make sure we start from the current cursor position, even
5237    * if it was offscreen, but don't queue more scrolls if we're
5238    * already behind.
5239    */
5240   if (text_view->pending_scroll)
5241     cancel_pending_scroll (text_view);
5242   else
5243     gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5244
5245   /* Validate the region that will be brought into view by the cursor motion
5246    */
5247   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5248                                     &old_insert, insert_mark);
5249
5250   if (count < 0)
5251     {
5252       gtk_text_view_get_first_para_iter (text_view, &anchor);
5253       y0 = adj->page_size;
5254       y1 = adj->page_size + count * adj->page_increment;
5255     }
5256   else
5257     {
5258       gtk_text_view_get_first_para_iter (text_view, &anchor);
5259       y0 = count * adj->page_increment + adj->page_size;
5260       y1 = 0;
5261     }
5262
5263   gtk_text_layout_validate_yrange (text_view->layout, &anchor, y0, y1);
5264   /* FIXME do we need to update the adjustment ranges here? */
5265
5266   new_insert = old_insert;
5267
5268   if (count < 0 && adj->value <= (adj->lower + 1e-12))
5269     {
5270       /* already at top, just be sure we are at offset 0 */
5271       gtk_text_buffer_get_start_iter (get_buffer (text_view), &new_insert);
5272       move_cursor (text_view, &new_insert, extend_selection);
5273     }
5274   else if (count > 0 && adj->value >= (adj->upper - adj->page_size - 1e-12))
5275     {
5276       /* already at bottom, just be sure we are at the end */
5277       gtk_text_buffer_get_end_iter (get_buffer (text_view), &new_insert);
5278       move_cursor (text_view, &new_insert, extend_selection);
5279     }
5280   else
5281     {
5282       gtk_text_view_get_virtual_cursor_pos (text_view, &cursor_x_pos, &cursor_y_pos);
5283
5284       oldval = adj->value;
5285       newval = adj->value;
5286
5287       newval += count * adj->page_increment;
5288
5289       set_adjustment_clamped (adj, newval);
5290       cursor_y_pos += adj->value - oldval;
5291
5292       gtk_text_layout_get_iter_at_pixel (text_view->layout, &new_insert, cursor_x_pos, cursor_y_pos);
5293       clamp_iter_onscreen (text_view, &new_insert);
5294       move_cursor (text_view, &new_insert, extend_selection);
5295
5296       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
5297     }
5298   
5299   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
5300    * only guarantees 1 pixel onscreen.
5301    */
5302   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5303   gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5304
5305   return !gtk_text_iter_equal (&old_insert, &new_insert);
5306 }
5307
5308 static gboolean
5309 gtk_text_view_scroll_hpages (GtkTextView *text_view,
5310                              gint         count,
5311                              gboolean     extend_selection)
5312 {
5313   gdouble newval;
5314   gdouble oldval;
5315   GtkAdjustment *adj;
5316   gint cursor_x_pos, cursor_y_pos;
5317   GtkTextMark *insert_mark;
5318   GtkTextIter old_insert;
5319   GtkTextIter new_insert;
5320   gint y, height;
5321   
5322   g_return_val_if_fail (text_view->hadjustment != NULL, FALSE);
5323
5324   adj = text_view->hadjustment;
5325
5326   insert_mark = gtk_text_buffer_get_insert (get_buffer (text_view));
5327
5328   /* Make sure we start from the current cursor position, even
5329    * if it was offscreen, but don't queue more scrolls if we're
5330    * already behind.
5331    */
5332   if (text_view->pending_scroll)
5333     cancel_pending_scroll (text_view);
5334   else
5335     gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5336
5337   /* Validate the line that we're moving within.
5338    */
5339   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5340                                     &old_insert, insert_mark);
5341
5342   gtk_text_layout_get_line_yrange (text_view->layout, &old_insert, &y, &height);
5343   gtk_text_layout_validate_yrange (text_view->layout, &old_insert, y, y + height);
5344   /* FIXME do we need to update the adjustment ranges here? */
5345
5346   new_insert = old_insert;
5347
5348   if (count < 0 && adj->value <= (adj->lower + 1e-12))
5349     {
5350       /* already at far left, just be sure we are at offset 0 */
5351       gtk_text_iter_set_line_offset (&new_insert, 0);
5352       move_cursor (text_view, &new_insert, extend_selection);
5353     }
5354   else if (count > 0 && adj->value >= (adj->upper - adj->page_size - 1e-12))
5355     {
5356       /* already at far right, just be sure we are at the end */
5357       if (!gtk_text_iter_ends_line (&new_insert))
5358           gtk_text_iter_forward_to_line_end (&new_insert);
5359       move_cursor (text_view, &new_insert, extend_selection);
5360     }
5361   else
5362     {
5363       gtk_text_view_get_virtual_cursor_pos (text_view, &cursor_x_pos, &cursor_y_pos);
5364
5365       oldval = adj->value;
5366       newval = adj->value;
5367
5368       newval += count * adj->page_increment;
5369
5370       set_adjustment_clamped (adj, newval);
5371       cursor_x_pos += adj->value - oldval;
5372
5373       gtk_text_layout_get_iter_at_pixel (text_view->layout, &new_insert, cursor_x_pos, cursor_y_pos);
5374       clamp_iter_onscreen (text_view, &new_insert);
5375       move_cursor (text_view, &new_insert, extend_selection);
5376
5377       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
5378     }
5379
5380   /*  FIXME for lines shorter than the overall widget width, this results in a
5381    *  "bounce" effect as we scroll to the right of the widget, then scroll
5382    *  back to get the end of the line onscreen.
5383    *      http://bugzilla.gnome.org/show_bug.cgi?id=68963
5384    */
5385   
5386   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
5387    * only guarantees 1 pixel onscreen.
5388    */
5389   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5390   gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5391
5392   return !gtk_text_iter_equal (&old_insert, &new_insert);
5393 }
5394
5395 static gboolean
5396 whitespace (gunichar ch, gpointer user_data)
5397 {
5398   return (ch == ' ' || ch == '\t');
5399 }
5400
5401 static gboolean
5402 not_whitespace (gunichar ch, gpointer user_data)
5403 {
5404   return !whitespace (ch, user_data);
5405 }
5406
5407 static gboolean
5408 find_whitepace_region (const GtkTextIter *center,
5409                        GtkTextIter *start, GtkTextIter *end)
5410 {
5411   *start = *center;
5412   *end = *center;
5413
5414   if (gtk_text_iter_backward_find_char (start, not_whitespace, NULL, NULL))
5415     gtk_text_iter_forward_char (start); /* we want the first whitespace... */
5416   if (whitespace (gtk_text_iter_get_char (end), NULL))
5417     gtk_text_iter_forward_find_char (end, not_whitespace, NULL, NULL);
5418
5419   return !gtk_text_iter_equal (start, end);
5420 }
5421
5422 static void
5423 gtk_text_view_insert_at_cursor (GtkTextView *text_view,
5424                                 const gchar *str)
5425 {
5426   if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
5427                                                      text_view->editable))
5428     {
5429       gtk_widget_error_bell (GTK_WIDGET (text_view));
5430     }
5431 }
5432
5433 static void
5434 gtk_text_view_delete_from_cursor (GtkTextView   *text_view,
5435                                   GtkDeleteType  type,
5436                                   gint           count)
5437 {
5438   GtkTextIter insert;
5439   GtkTextIter start;
5440   GtkTextIter end;
5441   gboolean leave_one = FALSE;
5442
5443   gtk_text_view_reset_im_context (text_view);
5444
5445   if (type == GTK_DELETE_CHARS)
5446     {
5447       /* Char delete deletes the selection, if one exists */
5448       if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
5449                                             text_view->editable))
5450         return;
5451     }
5452
5453   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5454                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5455
5456   start = insert;
5457   end = insert;
5458
5459   switch (type)
5460     {
5461     case GTK_DELETE_CHARS:
5462       gtk_text_iter_forward_cursor_positions (&end, count);
5463       break;
5464
5465     case GTK_DELETE_WORD_ENDS:
5466       if (count > 0)
5467         gtk_text_iter_forward_word_ends (&end, count);
5468       else if (count < 0)
5469         gtk_text_iter_backward_word_starts (&start, 0 - count);
5470       break;
5471
5472     case GTK_DELETE_WORDS:
5473       break;
5474
5475     case GTK_DELETE_DISPLAY_LINE_ENDS:
5476       break;
5477
5478     case GTK_DELETE_DISPLAY_LINES:
5479       break;
5480
5481     case GTK_DELETE_PARAGRAPH_ENDS:
5482       /* If we're already at a newline, we need to
5483        * simply delete that newline, instead of
5484        * moving to the next one.
5485        */
5486       if (gtk_text_iter_ends_line (&end))
5487         {
5488           gtk_text_iter_forward_line (&end);
5489           --count;
5490         }
5491
5492       while (count > 0)
5493         {
5494           if (!gtk_text_iter_forward_to_line_end (&end))
5495             break;
5496
5497           --count;
5498         }
5499
5500       /* FIXME figure out what a negative count means
5501          and support that */
5502       break;
5503
5504     case GTK_DELETE_PARAGRAPHS:
5505       if (count > 0)
5506         {
5507           gtk_text_iter_set_line_offset (&start, 0);
5508           gtk_text_iter_forward_to_line_end (&end);
5509
5510           /* Do the lines beyond the first. */
5511           while (count > 1)
5512             {
5513               gtk_text_iter_forward_to_line_end (&end);
5514
5515               --count;
5516             }
5517         }
5518
5519       /* FIXME negative count? */
5520
5521       break;
5522
5523     case GTK_DELETE_WHITESPACE:
5524       {
5525         find_whitepace_region (&insert, &start, &end);
5526       }
5527       break;
5528
5529     default:
5530       break;
5531     }
5532
5533   if (!gtk_text_iter_equal (&start, &end))
5534     {
5535       gtk_text_buffer_begin_user_action (get_buffer (text_view));
5536
5537       if (gtk_text_buffer_delete_interactive (get_buffer (text_view), &start, &end,
5538                                               text_view->editable))
5539         {
5540           if (leave_one)
5541             gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view),
5542                                                           " ", 1,
5543                                                           text_view->editable);
5544         }
5545       else
5546         {
5547           gtk_widget_error_bell (GTK_WIDGET (text_view));
5548         }
5549
5550       gtk_text_buffer_end_user_action (get_buffer (text_view));
5551       gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
5552
5553       DV(g_print (G_STRLOC": scrolling onscreen\n"));
5554       gtk_text_view_scroll_mark_onscreen (text_view,
5555                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
5556     }
5557   else
5558     {
5559       gtk_widget_error_bell (GTK_WIDGET (text_view));
5560     }
5561 }
5562
5563 static void
5564 gtk_text_view_backspace (GtkTextView *text_view)
5565 {
5566   GtkTextIter insert;
5567
5568   gtk_text_view_reset_im_context (text_view);
5569
5570   /* Backspace deletes the selection, if one exists */
5571   if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
5572                                         text_view->editable))
5573     return;
5574
5575   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5576                                     &insert,
5577                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5578
5579   if (gtk_text_buffer_backspace (get_buffer (text_view), &insert,
5580                                  TRUE, text_view->editable))
5581     {
5582       gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
5583       DV(g_print (G_STRLOC": scrolling onscreen\n"));
5584       gtk_text_view_scroll_mark_onscreen (text_view,
5585                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
5586     }
5587   else
5588     {
5589       gtk_widget_error_bell (GTK_WIDGET (text_view));
5590     }
5591 }
5592
5593 static void
5594 gtk_text_view_cut_clipboard (GtkTextView *text_view)
5595 {
5596   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
5597                                                       GDK_SELECTION_CLIPBOARD);
5598   
5599   gtk_text_buffer_cut_clipboard (get_buffer (text_view),
5600                                  clipboard,
5601                                  text_view->editable);
5602   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5603   gtk_text_view_scroll_mark_onscreen (text_view,
5604                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
5605 }
5606
5607 static void
5608 gtk_text_view_copy_clipboard (GtkTextView *text_view)
5609 {
5610   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
5611                                                       GDK_SELECTION_CLIPBOARD);
5612   
5613   gtk_text_buffer_copy_clipboard (get_buffer (text_view),
5614                                   clipboard);
5615
5616   /* on copy do not scroll, we are already onscreen */
5617 }
5618
5619 static void
5620 gtk_text_view_paste_clipboard (GtkTextView *text_view)
5621 {
5622   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
5623                                                       GDK_SELECTION_CLIPBOARD);
5624   
5625   gtk_text_buffer_paste_clipboard (get_buffer (text_view),
5626                                    clipboard,
5627                                    NULL,
5628                                    text_view->editable);
5629   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5630   gtk_text_view_scroll_mark_onscreen (text_view,
5631                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
5632 }
5633
5634 static void
5635 gtk_text_view_toggle_overwrite (GtkTextView *text_view)
5636 {
5637   if (text_view->text_window)
5638     text_window_invalidate_cursors (text_view->text_window);
5639
5640   text_view->overwrite_mode = !text_view->overwrite_mode;
5641
5642   if (text_view->layout)
5643     gtk_text_layout_set_overwrite_mode (text_view->layout,
5644                                         text_view->overwrite_mode && text_view->editable);
5645
5646   if (text_view->text_window)
5647     text_window_invalidate_cursors (text_view->text_window);
5648
5649   gtk_text_view_pend_cursor_blink (text_view);
5650
5651   g_object_notify (G_OBJECT (text_view), "overwrite");
5652 }
5653
5654 /**
5655  * gtk_text_view_get_overwrite:
5656  * @text_view: a #GtkTextView
5657  *
5658  * Returns whether the #GtkTextView is in overwrite mode or not.
5659  *
5660  * Return value: whether @text_view is in overwrite mode or not.
5661  * 
5662  * Since: 2.4
5663  **/
5664 gboolean
5665 gtk_text_view_get_overwrite (GtkTextView *text_view)
5666 {
5667   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
5668
5669   return text_view->overwrite_mode;
5670 }
5671
5672 /**
5673  * gtk_text_view_set_overwrite:
5674  * @text_view: a #GtkTextView
5675  * @overwrite: %TRUE to turn on overwrite mode, %FALSE to turn it off
5676  *
5677  * Changes the #GtkTextView overwrite mode.
5678  *
5679  * Since: 2.4
5680  **/
5681 void
5682 gtk_text_view_set_overwrite (GtkTextView *text_view,
5683                              gboolean     overwrite)
5684 {
5685   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
5686   overwrite = overwrite != FALSE;
5687
5688   if (text_view->overwrite_mode != overwrite)
5689     gtk_text_view_toggle_overwrite (text_view);
5690 }
5691
5692 /**
5693  * gtk_text_view_set_accepts_tab:
5694  * @text_view: A #GtkTextView
5695  * @accepts_tab: %TRUE if pressing the Tab key should insert a tab 
5696  *    character, %FALSE, if pressing the Tab key should move the 
5697  *    keyboard focus.
5698  * 
5699  * Sets the behavior of the text widget when the Tab key is pressed. 
5700  * If @accepts_tab is %TRUE, a tab character is inserted. If @accepts_tab 
5701  * is %FALSE the keyboard focus is moved to the next widget in the focus 
5702  * chain.
5703  * 
5704  * Since: 2.4
5705  **/
5706 void
5707 gtk_text_view_set_accepts_tab (GtkTextView *text_view,
5708                                gboolean     accepts_tab)
5709 {
5710   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
5711
5712   accepts_tab = accepts_tab != FALSE;
5713
5714   if (text_view->accepts_tab != accepts_tab)
5715     {
5716       text_view->accepts_tab = accepts_tab;
5717
5718       g_object_notify (G_OBJECT (text_view), "accepts-tab");
5719     }
5720 }
5721
5722 /**
5723  * gtk_text_view_get_accepts_tab:
5724  * @text_view: A #GtkTextView
5725  * 
5726  * Returns whether pressing the Tab key inserts a tab characters.
5727  * gtk_text_view_set_accepts_tab().
5728  * 
5729  * Return value: %TRUE if pressing the Tab key inserts a tab character, 
5730  *   %FALSE if pressing the Tab key moves the keyboard focus.
5731  * 
5732  * Since: 2.4
5733  **/
5734 gboolean
5735 gtk_text_view_get_accepts_tab (GtkTextView *text_view)
5736 {
5737   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
5738
5739   return text_view->accepts_tab;
5740 }
5741
5742 static void
5743 gtk_text_view_compat_move_focus (GtkTextView     *text_view,
5744                                  GtkDirectionType direction_type)
5745 {
5746   GSignalInvocationHint *hint = g_signal_get_invocation_hint (text_view);
5747
5748   /*  as of GTK+ 2.12, the "move-focus" signal has been moved to GtkWidget,
5749    *  the evil code below makes sure that both emitting the signal and
5750    *  calling the virtual function directly continue to work as expetcted
5751    */
5752
5753   if (hint->signal_id == g_signal_lookup ("move-focus", GTK_TYPE_WIDGET))
5754     {
5755       /*  if this is a signal emission, chain up  */
5756
5757       gboolean retval;
5758
5759       g_signal_chain_from_overridden_handler (text_view,
5760                                               direction_type, &retval);
5761     }
5762   else
5763     {
5764       /*  otherwise emit the signal, since somebody called the virtual
5765        *  function directly
5766        */
5767
5768       g_signal_emit_by_name (text_view, "move-focus", direction_type);
5769     }
5770 }
5771
5772 /*
5773  * Selections
5774  */
5775
5776 static void
5777 gtk_text_view_unselect (GtkTextView *text_view)
5778 {
5779   GtkTextIter insert;
5780
5781   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5782                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5783
5784   gtk_text_buffer_move_mark (get_buffer (text_view),
5785                              gtk_text_buffer_get_selection_bound (get_buffer (text_view)),
5786                              &insert);
5787 }
5788
5789 static void
5790 get_iter_at_pointer (GtkTextView *text_view,
5791                      GtkTextIter *iter,
5792                      gint        *x,
5793                      gint        *y)
5794 {
5795   gint xcoord, ycoord;
5796   GdkModifierType state;
5797
5798   gdk_window_get_pointer (text_view->text_window->bin_window,
5799                           &xcoord, &ycoord, &state);
5800   
5801   gtk_text_layout_get_iter_at_pixel (text_view->layout,
5802                                      iter,
5803                                      xcoord + text_view->xoffset,
5804                                      ycoord + text_view->yoffset);
5805   if (x)
5806     *x = xcoord;
5807
5808   if (y)
5809     *y = ycoord;
5810 }
5811
5812 static void
5813 move_mark_to_pointer_and_scroll (GtkTextView *text_view,
5814                                  const gchar *mark_name)
5815 {
5816   GtkTextIter newplace;
5817   GtkTextMark *mark;
5818
5819   get_iter_at_pointer (text_view, &newplace, NULL, NULL);
5820   
5821   mark = gtk_text_buffer_get_mark (get_buffer (text_view), mark_name);
5822   
5823   /* This may invalidate the layout */
5824   DV(g_print (G_STRLOC": move mark\n"));
5825   
5826   gtk_text_buffer_move_mark (get_buffer (text_view),
5827                              mark,
5828                              &newplace);
5829   
5830   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5831   gtk_text_view_scroll_mark_onscreen (text_view, mark);
5832
5833   DV (g_print ("first validate idle leaving %s is %d\n",
5834                G_STRLOC, text_view->first_validate_idle));
5835 }
5836
5837 static gboolean
5838 selection_scan_timeout (gpointer data)
5839 {
5840   GtkTextView *text_view;
5841
5842   text_view = GTK_TEXT_VIEW (data);
5843
5844   DV(g_print (G_STRLOC": calling move_mark_to_pointer_and_scroll\n"));
5845   gtk_text_view_scroll_mark_onscreen (text_view, 
5846                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
5847
5848   return TRUE; /* remain installed. */
5849 }
5850
5851 #define UPPER_OFFSET_ANCHOR 0.8
5852 #define LOWER_OFFSET_ANCHOR 0.2
5853
5854 static gboolean
5855 check_scroll (gdouble offset, GtkAdjustment *adj)
5856 {
5857   if ((offset > UPPER_OFFSET_ANCHOR &&
5858        adj->value + adj->page_size < adj->upper) ||
5859       (offset < LOWER_OFFSET_ANCHOR &&
5860        adj->value > adj->lower))
5861     return TRUE;
5862
5863   return FALSE;
5864 }
5865
5866 static gint
5867 drag_scan_timeout (gpointer data)
5868 {
5869   GtkTextView *text_view;
5870   GtkTextIter newplace;
5871   gint x, y, width, height;
5872   gdouble pointer_xoffset, pointer_yoffset;
5873
5874   text_view = GTK_TEXT_VIEW (data);
5875
5876   get_iter_at_pointer (text_view, &newplace, &x, &y);
5877   gdk_drawable_get_size (text_view->text_window->bin_window, &width, &height);
5878
5879   gtk_text_buffer_move_mark (get_buffer (text_view),
5880                              text_view->dnd_mark,
5881                              &newplace);
5882
5883   pointer_xoffset = (gdouble) x / width;
5884   pointer_yoffset = (gdouble) y / height;
5885
5886   if (check_scroll (pointer_xoffset, text_view->hadjustment) ||
5887       check_scroll (pointer_yoffset, text_view->vadjustment))
5888     {
5889       /* do not make offsets surpass lower nor upper anchors, this makes
5890        * scrolling speed relative to the distance of the pointer to the
5891        * anchors when it moves beyond them.
5892        */
5893       pointer_xoffset = CLAMP (pointer_xoffset, LOWER_OFFSET_ANCHOR, UPPER_OFFSET_ANCHOR);
5894       pointer_yoffset = CLAMP (pointer_yoffset, LOWER_OFFSET_ANCHOR, UPPER_OFFSET_ANCHOR);
5895
5896       gtk_text_view_scroll_to_mark (text_view,
5897                                     text_view->dnd_mark,
5898                                     0., TRUE, pointer_xoffset, pointer_yoffset);
5899     }
5900
5901   return TRUE;
5902 }
5903
5904 typedef enum 
5905 {
5906   SELECT_CHARACTERS,
5907   SELECT_WORDS,
5908   SELECT_LINES
5909 } SelectionGranularity;
5910
5911 /*
5912  * Move @start and @end to the boundaries of the selection unit (indicated by 
5913  * @granularity) which contained @start initially.
5914  * If the selction unit is SELECT_WORDS and @start is not contained in a word
5915  * the selection is extended to all the white spaces between the end of the 
5916  * word preceding @start and the start of the one following.
5917  */
5918 static void
5919 extend_selection (GtkTextView *text_view, 
5920                   SelectionGranularity granularity, 
5921                   GtkTextIter *start, 
5922                   GtkTextIter *end)
5923 {
5924   *end = *start;
5925
5926   if (granularity == SELECT_WORDS) 
5927     {
5928       if (gtk_text_iter_inside_word (start))
5929         {
5930           if (!gtk_text_iter_starts_word (start))
5931             gtk_text_iter_backward_visible_word_start (start);
5932           
5933           if (!gtk_text_iter_ends_word (end))
5934             {
5935               if (!gtk_text_iter_forward_visible_word_end (end))
5936                 gtk_text_iter_forward_to_end (end);
5937             }
5938         }
5939       else
5940         {
5941           GtkTextIter tmp;
5942
5943           tmp = *start;
5944           if (gtk_text_iter_backward_visible_word_start (&tmp))
5945             gtk_text_iter_forward_visible_word_end (&tmp);
5946
5947           if (gtk_text_iter_get_line (&tmp) == gtk_text_iter_get_line (start))
5948             *start = tmp;
5949           else
5950             gtk_text_iter_set_line_offset (start, 0);
5951
5952           tmp = *end;
5953           if (!gtk_text_iter_forward_visible_word_end (&tmp))
5954             gtk_text_iter_forward_to_end (&tmp);
5955
5956           if (gtk_text_iter_ends_word (&tmp))
5957             gtk_text_iter_backward_visible_word_start (&tmp);
5958
5959           if (gtk_text_iter_get_line (&tmp) == gtk_text_iter_get_line (end))
5960             *end = tmp;
5961           else
5962             gtk_text_iter_forward_to_line_end (end);
5963         }
5964     }
5965   else if (granularity == SELECT_LINES) 
5966     {
5967       if (gtk_text_view_starts_display_line (text_view, start))
5968         {
5969           /* If on a display line boundary, we assume the user
5970            * clicked off the end of a line and we therefore select
5971            * the line before the boundary.
5972            */
5973           gtk_text_view_backward_display_line_start (text_view, start);
5974         }
5975       else
5976         {
5977           /* start isn't on the start of a line, so we move it to the
5978            * start, and move end to the end unless it's already there.
5979            */
5980           gtk_text_view_backward_display_line_start (text_view, start);
5981           
5982           if (!gtk_text_view_starts_display_line (text_view, end))
5983             gtk_text_view_forward_display_line_end (text_view, end);
5984         }
5985     }
5986 }
5987  
5988
5989 typedef struct
5990 {
5991   SelectionGranularity granularity;
5992   GtkTextMark *orig_start;
5993   GtkTextMark *orig_end;
5994 } SelectionData;
5995
5996 static void
5997 selection_data_free (SelectionData *data)
5998 {
5999   if (data->orig_start != NULL)
6000     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (data->orig_start),
6001                                  data->orig_start);
6002   if (data->orig_end != NULL)
6003     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (data->orig_end),
6004                                  data->orig_end);
6005   g_free (data);
6006 }
6007
6008 static gint
6009 selection_motion_event_handler (GtkTextView    *text_view, 
6010                                 GdkEventMotion *event, 
6011                                 SelectionData  *data)
6012 {
6013   gdk_event_request_motions (event);
6014
6015   if (data->granularity == SELECT_CHARACTERS) 
6016     {
6017       move_mark_to_pointer_and_scroll (text_view, "insert");
6018     }
6019   else 
6020     {
6021       GtkTextIter cursor, start, end;
6022       GtkTextIter orig_start, orig_end;
6023       GtkTextBuffer *buffer;
6024       
6025       buffer = get_buffer (text_view);
6026
6027       gtk_text_buffer_get_iter_at_mark (buffer, &orig_start, data->orig_start);
6028       gtk_text_buffer_get_iter_at_mark (buffer, &orig_end, data->orig_end);
6029
6030       get_iter_at_pointer (text_view, &cursor, NULL, NULL);
6031       
6032       start = cursor;
6033       extend_selection (text_view, data->granularity, &start, &end);
6034
6035       /* either the selection extends to the front, or end (or not) */
6036       if (gtk_text_iter_compare (&cursor, &orig_start) < 0)
6037         gtk_text_buffer_select_range (buffer, &start, &orig_end);
6038       else
6039         gtk_text_buffer_select_range (buffer, &end, &orig_start);
6040
6041       gtk_text_view_scroll_mark_onscreen (text_view, 
6042                                           gtk_text_buffer_get_insert (buffer));
6043     }
6044
6045   /* If we had to scroll offscreen, insert a timeout to do so
6046    * again. Note that in the timeout, even if the mouse doesn't
6047    * move, due to this scroll xoffset/yoffset will have changed
6048    * and we'll need to scroll again.
6049    */
6050   if (text_view->scroll_timeout != 0) /* reset on every motion event */
6051     g_source_remove (text_view->scroll_timeout);
6052   
6053   text_view->scroll_timeout =
6054     gdk_threads_add_timeout (50, selection_scan_timeout, text_view);
6055
6056   return TRUE;
6057 }
6058
6059 static void
6060 gtk_text_view_start_selection_drag (GtkTextView       *text_view,
6061                                     const GtkTextIter *iter,
6062                                     GdkEventButton    *button)
6063 {
6064   GtkTextIter cursor, ins, bound;
6065   GtkTextIter orig_start, orig_end;
6066   GtkTextBuffer *buffer;
6067   SelectionData *data;
6068
6069   if (text_view->selection_drag_handler != 0)
6070     return;
6071   
6072   data = g_new0 (SelectionData, 1);
6073
6074   if (button->type == GDK_2BUTTON_PRESS)
6075     data->granularity = SELECT_WORDS;
6076   else if (button->type == GDK_3BUTTON_PRESS)
6077     data->granularity = SELECT_LINES;
6078   else 
6079     data->granularity = SELECT_CHARACTERS;
6080
6081   gtk_grab_add (GTK_WIDGET (text_view));
6082
6083   buffer = get_buffer (text_view);
6084   
6085   cursor = *iter;
6086   ins = cursor;
6087   
6088   extend_selection (text_view, data->granularity, &ins, &bound);
6089   orig_start = ins;
6090   orig_end = bound;
6091
6092   if (button->state & GDK_SHIFT_MASK)
6093     {
6094       /* Extend selection */
6095       GtkTextIter old_ins, old_bound;
6096       GtkTextIter old_start, old_end;
6097
6098       gtk_text_buffer_get_iter_at_mark (buffer, &old_ins, gtk_text_buffer_get_insert (buffer));
6099       gtk_text_buffer_get_iter_at_mark (buffer, &old_bound, gtk_text_buffer_get_selection_bound (buffer));
6100       old_start = old_ins;
6101       old_end = old_bound;
6102       gtk_text_iter_order (&old_start, &old_end);
6103       
6104       /* move the front cursor, if the mouse is in front of the selection. Should the
6105        * cursor however be inside the selection (this happens on tripple click) then we
6106        * move the side which was last moved (current insert mark) */
6107       if (gtk_text_iter_compare (&cursor, &old_start) <= 0 ||
6108           (gtk_text_iter_compare (&cursor, &old_end) < 0 && 
6109            gtk_text_iter_compare (&old_ins, &old_bound) <= 0))
6110         {
6111           bound = old_end;
6112           orig_start = old_end;
6113           orig_end = old_end;
6114         }
6115       else
6116         {
6117           ins = bound;
6118           bound = old_start;
6119           orig_end = bound;
6120           orig_start = bound;
6121         }
6122     }
6123
6124   gtk_text_buffer_select_range (buffer, &ins, &bound);
6125
6126   gtk_text_iter_order (&orig_start, &orig_end);
6127   data->orig_start = gtk_text_buffer_create_mark (buffer, NULL,
6128                                                   &orig_start, TRUE);
6129   data->orig_end = gtk_text_buffer_create_mark (buffer, NULL,
6130                                                 &orig_end, TRUE);
6131
6132   gtk_text_view_check_cursor_blink (text_view);
6133
6134   text_view->selection_drag_handler = g_signal_connect_data (text_view,
6135                                                              "motion_notify_event",
6136                                                              G_CALLBACK (selection_motion_event_handler),
6137                                                              data,
6138                                                              (GClosureNotify) selection_data_free, 0);  
6139 }
6140
6141 /* returns whether we were really dragging */
6142 static gboolean
6143 gtk_text_view_end_selection_drag (GtkTextView    *text_view) 
6144 {
6145   if (text_view->selection_drag_handler == 0)
6146     return FALSE;
6147
6148   g_signal_handler_disconnect (text_view, text_view->selection_drag_handler);
6149   text_view->selection_drag_handler = 0;
6150
6151   if (text_view->scroll_timeout != 0)
6152     {
6153       g_source_remove (text_view->scroll_timeout);
6154       text_view->scroll_timeout = 0;
6155     }
6156
6157   gtk_grab_remove (GTK_WIDGET (text_view));
6158
6159   return TRUE;
6160 }
6161
6162 /*
6163  * Layout utils
6164  */
6165
6166 static void
6167 gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
6168                                          GtkTextAttributes  *values,
6169                                          GtkStyle           *style)
6170 {
6171   values->appearance.bg_color = style->base[GTK_STATE_NORMAL];
6172   values->appearance.fg_color = style->text[GTK_STATE_NORMAL];
6173
6174   if (values->font)
6175     pango_font_description_free (values->font);
6176
6177   values->font = pango_font_description_copy (style->font_desc);
6178 }
6179
6180 static void
6181 gtk_text_view_check_keymap_direction (GtkTextView *text_view)
6182 {
6183   if (text_view->layout)
6184     {
6185       GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
6186       GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (text_view)));
6187       GtkTextDirection new_cursor_dir;
6188       GtkTextDirection new_keyboard_dir;
6189       gboolean split_cursor;
6190
6191       g_object_get (settings,
6192                     "gtk-split-cursor", &split_cursor,
6193                     NULL);
6194       
6195       if (gdk_keymap_get_direction (keymap) == PANGO_DIRECTION_RTL)
6196         new_keyboard_dir = GTK_TEXT_DIR_RTL;
6197       else
6198         new_keyboard_dir  = GTK_TEXT_DIR_LTR;
6199   
6200       if (split_cursor)
6201         new_cursor_dir = GTK_TEXT_DIR_NONE;
6202       else
6203         new_cursor_dir = new_keyboard_dir;
6204       
6205       gtk_text_layout_set_cursor_direction (text_view->layout, new_cursor_dir);
6206       gtk_text_layout_set_keyboard_direction (text_view->layout, new_keyboard_dir);
6207     }
6208 }
6209
6210 static void
6211 gtk_text_view_ensure_layout (GtkTextView *text_view)
6212 {
6213   GtkWidget *widget;
6214
6215   widget = GTK_WIDGET (text_view);
6216
6217   if (text_view->layout == NULL)
6218     {
6219       GtkTextAttributes *style;
6220       PangoContext *ltr_context, *rtl_context;
6221       GSList *tmp_list;
6222
6223       DV(g_print(G_STRLOC"\n"));
6224       
6225       text_view->layout = gtk_text_layout_new ();
6226
6227       g_signal_connect (text_view->layout,
6228                         "invalidated",
6229                         G_CALLBACK (invalidated_handler),
6230                         text_view);
6231
6232       g_signal_connect (text_view->layout,
6233                         "changed",
6234                         G_CALLBACK (changed_handler),
6235                         text_view);
6236
6237       g_signal_connect (text_view->layout,
6238                         "allocate_child",
6239                         G_CALLBACK (gtk_text_view_child_allocated),
6240                         text_view);
6241       
6242       if (get_buffer (text_view))
6243         gtk_text_layout_set_buffer (text_view->layout, get_buffer (text_view));
6244
6245       if ((GTK_WIDGET_HAS_FOCUS (text_view) && text_view->cursor_visible))
6246         gtk_text_view_pend_cursor_blink (text_view);
6247       else
6248         gtk_text_layout_set_cursor_visible (text_view->layout, FALSE);
6249
6250       gtk_text_layout_set_overwrite_mode (text_view->layout,
6251                                           text_view->overwrite_mode && text_view->editable);
6252
6253       ltr_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
6254       pango_context_set_base_dir (ltr_context, PANGO_DIRECTION_LTR);
6255       rtl_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
6256       pango_context_set_base_dir (rtl_context, PANGO_DIRECTION_RTL);
6257
6258       gtk_text_layout_set_contexts (text_view->layout, ltr_context, rtl_context);
6259
6260       g_object_unref (ltr_context);
6261       g_object_unref (rtl_context);
6262
6263       gtk_text_view_check_keymap_direction (text_view);
6264
6265       style = gtk_text_attributes_new ();
6266
6267       gtk_widget_ensure_style (widget);
6268       gtk_text_view_set_attributes_from_style (text_view,
6269                                                style, widget->style);
6270
6271       style->pixels_above_lines = text_view->pixels_above_lines;
6272       style->pixels_below_lines = text_view->pixels_below_lines;
6273       style->pixels_inside_wrap = text_view->pixels_inside_wrap;
6274       style->left_margin = text_view->left_margin;
6275       style->right_margin = text_view->right_margin;
6276       style->indent = text_view->indent;
6277       style->tabs = text_view->tabs ? pango_tab_array_copy (text_view->tabs) : NULL;
6278
6279       style->wrap_mode = text_view->wrap_mode;
6280       style->justification = text_view->justify;
6281       style->direction = gtk_widget_get_direction (GTK_WIDGET (text_view));
6282
6283       gtk_text_layout_set_default_style (text_view->layout, style);
6284
6285       gtk_text_attributes_unref (style);
6286
6287       /* Set layout for all anchored children */
6288
6289       tmp_list = text_view->children;
6290       while (tmp_list != NULL)
6291         {
6292           GtkTextViewChild *vc = tmp_list->data;
6293
6294           if (vc->anchor)
6295             {
6296               gtk_text_anchored_child_set_layout (vc->widget,
6297                                                   text_view->layout);
6298               /* vc may now be invalid! */
6299             }
6300
6301           tmp_list = g_slist_next (tmp_list);
6302         }
6303
6304       gtk_text_view_invalidate (text_view);
6305     }
6306 }
6307
6308 /**
6309  * gtk_text_view_get_default_attributes:
6310  * @text_view: a #GtkTextView
6311  * 
6312  * Obtains a copy of the default text attributes. These are the
6313  * attributes used for text unless a tag overrides them.
6314  * You'd typically pass the default attributes in to
6315  * gtk_text_iter_get_attributes() in order to get the
6316  * attributes in effect at a given text position.
6317  *
6318  * The return value is a copy owned by the caller of this function,
6319  * and should be freed.
6320  * 
6321  * Return value: a new #GtkTextAttributes
6322  **/
6323 GtkTextAttributes*
6324 gtk_text_view_get_default_attributes (GtkTextView *text_view)
6325 {
6326   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
6327   
6328   gtk_text_view_ensure_layout (text_view);
6329
6330   return gtk_text_attributes_copy (text_view->layout->default_style);
6331 }
6332
6333 static void
6334 gtk_text_view_destroy_layout (GtkTextView *text_view)
6335 {
6336   if (text_view->layout)
6337     {
6338       GSList *tmp_list;
6339
6340       gtk_text_view_remove_validate_idles (text_view);
6341
6342       g_signal_handlers_disconnect_by_func (text_view->layout,
6343                                             invalidated_handler,
6344                                             text_view);
6345       g_signal_handlers_disconnect_by_func (text_view->layout,
6346                                             changed_handler, 
6347                                             text_view);
6348       
6349       /* Remove layout from all anchored children */
6350       tmp_list = text_view->children;
6351       while (tmp_list != NULL)
6352         {
6353           GtkTextViewChild *vc = tmp_list->data;
6354
6355           if (vc->anchor)
6356             {
6357               gtk_text_anchored_child_set_layout (vc->widget, NULL);
6358               /* vc may now be invalid! */
6359             }
6360
6361           tmp_list = g_slist_next (tmp_list);
6362         }
6363       
6364       gtk_text_view_stop_cursor_blink (text_view);
6365       gtk_text_view_end_selection_drag (text_view);
6366
6367       g_object_unref (text_view->layout);
6368       text_view->layout = NULL;
6369     }
6370 }
6371
6372 static void
6373 gtk_text_view_reset_im_context (GtkTextView *text_view)
6374 {
6375   if (text_view->need_im_reset)
6376     {
6377       text_view->need_im_reset = FALSE;
6378       gtk_im_context_reset (text_view->im_context);
6379     }
6380 }
6381
6382 /*
6383  * DND feature
6384  */
6385
6386 static void
6387 drag_begin_cb (GtkWidget      *widget,
6388                GdkDragContext *context,
6389                gpointer        data)
6390 {
6391   GtkTextView   *text_view = GTK_TEXT_VIEW (widget);
6392   GtkTextBuffer *buffer = gtk_text_view_get_buffer (text_view);
6393   GtkTextIter    start;
6394   GtkTextIter    end;
6395   GdkPixmap     *pixmap = NULL;
6396
6397   g_signal_handlers_disconnect_by_func (widget, drag_begin_cb, NULL);
6398
6399   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
6400     pixmap = _gtk_text_util_create_rich_drag_icon (widget, buffer, &start, &end);
6401
6402   if (pixmap)
6403     {
6404       gtk_drag_set_icon_pixmap (context,
6405                                 gdk_drawable_get_colormap (pixmap),
6406                                 pixmap,
6407                                 NULL,
6408                                 -2, -2);
6409       g_object_unref (pixmap);
6410     }
6411   else
6412     {
6413       gtk_drag_set_icon_default (context);
6414     }
6415 }
6416
6417 static void
6418 gtk_text_view_start_selection_dnd (GtkTextView       *text_view,
6419                                    const GtkTextIter *iter,
6420                                    GdkEventMotion    *event)
6421 {
6422   GtkTargetList *target_list;
6423
6424   text_view->drag_start_x = -1;
6425   text_view->drag_start_y = -1;
6426   text_view->pending_place_cursor_button = 0;
6427
6428   target_list = gtk_text_buffer_get_copy_target_list (get_buffer (text_view));
6429
6430   g_signal_connect (text_view, "drag_begin",
6431                     G_CALLBACK (drag_begin_cb), NULL);
6432   gtk_drag_begin (GTK_WIDGET (text_view), target_list,
6433                   GDK_ACTION_COPY | GDK_ACTION_MOVE,
6434                   1, (GdkEvent*)event);
6435 }
6436
6437 static void
6438 gtk_text_view_drag_begin (GtkWidget        *widget,
6439                           GdkDragContext   *context)
6440 {
6441   /* do nothing */
6442 }
6443
6444 static void
6445 gtk_text_view_drag_end (GtkWidget        *widget,
6446                         GdkDragContext   *context)
6447 {
6448 }
6449
6450 static void
6451 gtk_text_view_drag_data_get (GtkWidget        *widget,
6452                              GdkDragContext   *context,
6453                              GtkSelectionData *selection_data,
6454                              guint             info,
6455                              guint             time)
6456 {
6457   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
6458   GtkTextBuffer *buffer = gtk_text_view_get_buffer (text_view);
6459
6460   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
6461     {
6462       gtk_selection_data_set (selection_data,
6463                               gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"),
6464                               8, /* bytes */
6465                               (void*)&buffer,
6466                               sizeof (buffer));
6467     }
6468   else if (info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
6469     {
6470       GtkTextIter start;
6471       GtkTextIter end;
6472       guint8 *str = NULL;
6473       gsize len;
6474
6475       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
6476         {
6477           /* Extract the selected text */
6478           str = gtk_text_buffer_serialize (buffer, buffer,
6479                                            selection_data->target,
6480                                            &start, &end,
6481                                            &len);
6482         }
6483
6484       if (str)
6485         {
6486           gtk_selection_data_set (selection_data,
6487                                   selection_data->target,
6488                                   8, /* bytes */
6489                                   (guchar *) str, len);
6490           g_free (str);
6491         }
6492     }
6493   else
6494     {
6495       GtkTextIter start;
6496       GtkTextIter end;
6497       gchar *str = NULL;
6498
6499       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
6500         {
6501           /* Extract the selected text */
6502           str = gtk_text_iter_get_visible_text (&start, &end);
6503         }
6504
6505       if (str)
6506         {
6507           gtk_selection_data_set_text (selection_data, str, -1);
6508           g_free (str);
6509         }
6510     }
6511 }
6512
6513 static void
6514 gtk_text_view_drag_data_delete (GtkWidget        *widget,
6515                                 GdkDragContext   *context)
6516 {
6517   gtk_text_buffer_delete_selection (GTK_TEXT_VIEW (widget)->buffer,
6518                                     TRUE, GTK_TEXT_VIEW (widget)->editable);
6519 }
6520
6521 static void
6522 gtk_text_view_drag_leave (GtkWidget        *widget,
6523                           GdkDragContext   *context,
6524                           guint             time)
6525 {
6526   GtkTextView *text_view;
6527
6528   text_view = GTK_TEXT_VIEW (widget);
6529
6530   gtk_text_mark_set_visible (text_view->dnd_mark, FALSE);
6531   
6532   if (text_view->scroll_timeout != 0)
6533     g_source_remove (text_view->scroll_timeout);
6534
6535   text_view->scroll_timeout = 0;
6536 }
6537
6538 static gboolean
6539 gtk_text_view_drag_motion (GtkWidget        *widget,
6540                            GdkDragContext   *context,
6541                            gint              x,
6542                            gint              y,
6543                            guint             time)
6544 {
6545   GtkTextIter newplace;
6546   GtkTextView *text_view;
6547   GtkTextIter start;
6548   GtkTextIter end;
6549   GdkRectangle target_rect;
6550   gint bx, by;
6551   GdkAtom target;
6552   GdkDragAction suggested_action = 0;
6553   
6554   text_view = GTK_TEXT_VIEW (widget);
6555
6556   target_rect = text_view->text_window->allocation;
6557   
6558   if (x < target_rect.x ||
6559       y < target_rect.y ||
6560       x > (target_rect.x + target_rect.width) ||
6561       y > (target_rect.y + target_rect.height))
6562     return FALSE; /* outside the text window, allow parent widgets to handle event */
6563
6564   gtk_text_view_window_to_buffer_coords (text_view,
6565                                          GTK_TEXT_WINDOW_WIDGET,
6566                                          x, y,
6567                                          &bx, &by);
6568
6569   gtk_text_layout_get_iter_at_pixel (text_view->layout,
6570                                      &newplace,
6571                                      bx, by);  
6572
6573   target = gtk_drag_dest_find_target (widget, context,
6574                                       gtk_drag_dest_get_target_list (widget));
6575
6576   if (target == GDK_NONE)
6577     {
6578       /* can't accept any of the offered targets */
6579     }                                 
6580   else if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
6581                                                  &start, &end) &&
6582            gtk_text_iter_compare (&newplace, &start) >= 0 &&
6583            gtk_text_iter_compare (&newplace, &end) <= 0)
6584     {
6585       /* We're inside the selection. */
6586     }
6587   else
6588     {      
6589       if (gtk_text_iter_can_insert (&newplace, text_view->editable))
6590         {
6591           GtkWidget *source_widget;
6592           
6593           suggested_action = context->suggested_action;
6594           
6595           source_widget = gtk_drag_get_source_widget (context);
6596           
6597           if (source_widget == widget)
6598             {
6599               /* Default to MOVE, unless the user has
6600                * pressed ctrl or alt to affect available actions
6601                */
6602               if ((context->actions & GDK_ACTION_MOVE) != 0)
6603                 suggested_action = GDK_ACTION_MOVE;
6604             }
6605         }
6606       else
6607         {
6608           /* Can't drop here. */
6609         }
6610     }
6611
6612   if (suggested_action != 0)
6613     {
6614       gtk_text_mark_set_visible (text_view->dnd_mark,
6615                                  text_view->cursor_visible);
6616       
6617       gdk_drag_status (context, suggested_action, time);
6618     }
6619   else
6620     {
6621       gdk_drag_status (context, 0, time);
6622       gtk_text_mark_set_visible (text_view->dnd_mark, FALSE);
6623     }
6624       
6625   if (!text_view->scroll_timeout)
6626     text_view->scroll_timeout =
6627       gdk_threads_add_timeout (100, drag_scan_timeout, text_view);
6628
6629   /* TRUE return means don't propagate the drag motion to parent
6630    * widgets that may also be drop sites.
6631    */
6632   return TRUE;
6633 }
6634
6635 static gboolean
6636 gtk_text_view_drag_drop (GtkWidget        *widget,
6637                          GdkDragContext   *context,
6638                          gint              x,
6639                          gint              y,
6640                          guint             time)
6641 {
6642   GtkTextView *text_view;
6643   GtkTextIter drop_point;
6644   GdkAtom target = GDK_NONE;
6645   
6646   text_view = GTK_TEXT_VIEW (widget);
6647   
6648   if (text_view->scroll_timeout != 0)
6649     g_source_remove (text_view->scroll_timeout);
6650
6651   text_view->scroll_timeout = 0;
6652
6653   gtk_text_mark_set_visible (text_view->dnd_mark, FALSE);
6654
6655   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
6656                                     &drop_point,
6657                                     text_view->dnd_mark);
6658
6659   if (gtk_text_iter_can_insert (&drop_point, text_view->editable))
6660     target = gtk_drag_dest_find_target (widget, context, NULL);
6661
6662   if (target != GDK_NONE)
6663     gtk_drag_get_data (widget, context, target, time);
6664   else
6665     gtk_drag_finish (context, FALSE, FALSE, time);
6666
6667   return TRUE;
6668 }
6669
6670 static void
6671 insert_text_data (GtkTextView      *text_view,
6672                   GtkTextIter      *drop_point,
6673                   GtkSelectionData *selection_data)
6674 {
6675   guchar *str;
6676
6677   str = gtk_selection_data_get_text (selection_data);
6678
6679   if (str)
6680     {
6681       if (!gtk_text_buffer_insert_interactive (get_buffer (text_view),
6682                                                drop_point, (gchar *) str, -1,
6683                                                text_view->editable))
6684         {
6685           gtk_widget_error_bell (GTK_WIDGET (text_view));
6686         }
6687
6688       g_free (str);
6689     }
6690 }
6691
6692 static void
6693 gtk_text_view_drag_data_received (GtkWidget        *widget,
6694                                   GdkDragContext   *context,
6695                                   gint              x,
6696                                   gint              y,
6697                                   GtkSelectionData *selection_data,
6698                                   guint             info,
6699                                   guint             time)
6700 {
6701   GtkTextIter drop_point;
6702   GtkTextView *text_view;
6703   gboolean success = FALSE;
6704   GtkTextBuffer *buffer = NULL;
6705
6706   text_view = GTK_TEXT_VIEW (widget);
6707
6708   if (!text_view->dnd_mark)
6709     goto done;
6710
6711   buffer = get_buffer (text_view);
6712
6713   gtk_text_buffer_get_iter_at_mark (buffer,
6714                                     &drop_point,
6715                                     text_view->dnd_mark);
6716   
6717   if (!gtk_text_iter_can_insert (&drop_point, text_view->editable))
6718     goto done;
6719
6720   success = TRUE;
6721
6722   gtk_text_buffer_begin_user_action (buffer);
6723
6724   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
6725     {
6726       GtkTextBuffer *src_buffer = NULL;
6727       GtkTextIter start, end;
6728       gboolean copy_tags = TRUE;
6729
6730       if (selection_data->length != sizeof (src_buffer))
6731         return;
6732
6733       memcpy (&src_buffer, selection_data->data, sizeof (src_buffer));
6734
6735       if (src_buffer == NULL)
6736         return;
6737
6738       g_return_if_fail (GTK_IS_TEXT_BUFFER (src_buffer));
6739
6740       if (gtk_text_buffer_get_tag_table (src_buffer) !=
6741           gtk_text_buffer_get_tag_table (buffer))
6742         {
6743           /*  try to find a suitable rich text target instead  */
6744           GdkAtom *atoms;
6745           gint     n_atoms;
6746           GList   *list;
6747           GdkAtom  target = GDK_NONE;
6748
6749           copy_tags = FALSE;
6750
6751           atoms = gtk_text_buffer_get_deserialize_formats (buffer, &n_atoms);
6752
6753           for (list = context->targets; list; list = g_list_next (list))
6754             {
6755               gint i;
6756
6757               for (i = 0; i < n_atoms; i++)
6758                 if (GUINT_TO_POINTER (atoms[i]) == list->data)
6759                   {
6760                     target = atoms[i];
6761                     break;
6762                   }
6763             }
6764
6765           g_free (atoms);
6766
6767           if (target != GDK_NONE)
6768             {
6769               gtk_drag_get_data (widget, context, target, time);
6770               gtk_text_buffer_end_user_action (buffer);
6771               return;
6772             }
6773         }
6774
6775       if (gtk_text_buffer_get_selection_bounds (src_buffer,
6776                                                 &start,
6777                                                 &end))
6778         {
6779           if (copy_tags)
6780             gtk_text_buffer_insert_range_interactive (buffer,
6781                                                       &drop_point,
6782                                                       &start,
6783                                                       &end,
6784                                                       text_view->editable);
6785           else
6786             {
6787               gchar *str;
6788
6789               str = gtk_text_iter_get_visible_text (&start, &end);
6790               gtk_text_buffer_insert_interactive (buffer,
6791                                                   &drop_point, str, -1,
6792                                                   text_view->editable);
6793               g_free (str);
6794             }
6795         }
6796     }
6797   else if (selection_data->length > 0 &&
6798            info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
6799     {
6800       gboolean retval;
6801       GError *error = NULL;
6802
6803       retval = gtk_text_buffer_deserialize (buffer, buffer,
6804                                             selection_data->target,
6805                                             &drop_point,
6806                                             (guint8 *) selection_data->data,
6807                                             selection_data->length,
6808                                             &error);
6809
6810       if (!retval)
6811         {
6812           g_warning ("error pasting: %s\n", error->message);
6813           g_clear_error (&error);
6814         }
6815     }
6816   else
6817     insert_text_data (text_view, &drop_point, selection_data);
6818
6819  done:
6820   gtk_drag_finish (context, success,
6821                    success && context->action == GDK_ACTION_MOVE,
6822                    time);
6823
6824   if (success)
6825     {
6826       gtk_text_buffer_get_iter_at_mark (buffer,
6827                                         &drop_point,
6828                                         text_view->dnd_mark);
6829       gtk_text_buffer_place_cursor (buffer, &drop_point);
6830
6831       gtk_text_buffer_end_user_action (buffer);
6832     }
6833 }
6834
6835 static GtkAdjustment*
6836 get_hadjustment (GtkTextView *text_view)
6837 {
6838   if (text_view->hadjustment == NULL)
6839     gtk_text_view_set_scroll_adjustments (text_view,
6840                                           NULL, /* forces creation */
6841                                           text_view->vadjustment);
6842
6843   return text_view->hadjustment;
6844 }
6845
6846 static GtkAdjustment*
6847 get_vadjustment (GtkTextView *text_view)
6848 {
6849   if (text_view->vadjustment == NULL)
6850     gtk_text_view_set_scroll_adjustments (text_view,
6851                                           text_view->hadjustment,
6852                                           NULL); /* forces creation */
6853   return text_view->vadjustment;
6854 }
6855
6856
6857 static void
6858 gtk_text_view_set_scroll_adjustments (GtkTextView   *text_view,
6859                                       GtkAdjustment *hadj,
6860                                       GtkAdjustment *vadj)
6861 {
6862   gboolean need_adjust = FALSE;
6863
6864   if (hadj)
6865     g_return_if_fail (GTK_IS_ADJUSTMENT (hadj));
6866   else
6867     hadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
6868   if (vadj)
6869     g_return_if_fail (GTK_IS_ADJUSTMENT (vadj));
6870   else
6871     vadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
6872
6873   if (text_view->hadjustment && (text_view->hadjustment != hadj))
6874     {
6875       g_signal_handlers_disconnect_by_func (text_view->hadjustment,
6876                                             gtk_text_view_value_changed,
6877                                             text_view);
6878       g_object_unref (text_view->hadjustment);
6879     }
6880
6881   if (text_view->vadjustment && (text_view->vadjustment != vadj))
6882     {
6883       g_signal_handlers_disconnect_by_func (text_view->vadjustment,
6884                                             gtk_text_view_value_changed,
6885                                             text_view);
6886       g_object_unref (text_view->vadjustment);
6887     }
6888
6889   if (text_view->hadjustment != hadj)
6890     {
6891       text_view->hadjustment = hadj;
6892       g_object_ref_sink (text_view->hadjustment);
6893       
6894       g_signal_connect (text_view->hadjustment, "value-changed",
6895                         G_CALLBACK (gtk_text_view_value_changed),
6896                         text_view);
6897       need_adjust = TRUE;
6898     }
6899
6900   if (text_view->vadjustment != vadj)
6901     {
6902       text_view->vadjustment = vadj;
6903       g_object_ref_sink (text_view->vadjustment);
6904       
6905       g_signal_connect (text_view->vadjustment, "value-changed",
6906                         G_CALLBACK (gtk_text_view_value_changed),
6907                         text_view);
6908       need_adjust = TRUE;
6909     }
6910
6911   if (need_adjust)
6912     gtk_text_view_value_changed (NULL, text_view);
6913 }
6914
6915 /* FIXME this adjust_allocation is a big cut-and-paste from
6916  * GtkCList, needs to be some "official" way to do this
6917  * factored out.
6918  */
6919 typedef struct
6920 {
6921   GdkWindow *window;
6922   int dx;
6923   int dy;
6924 } ScrollData;
6925
6926 /* The window to which widget->window is relative */
6927 #define ALLOCATION_WINDOW(widget)               \
6928    (GTK_WIDGET_NO_WINDOW (widget) ?             \
6929     (widget)->window :                          \
6930      gdk_window_get_parent ((widget)->window))
6931
6932 static void
6933 adjust_allocation_recurse (GtkWidget *widget,
6934                            gpointer   data)
6935 {
6936   ScrollData *scroll_data = data;
6937
6938   /* Need to really size allocate instead of just poking
6939    * into widget->allocation if the widget is not realized.
6940    * FIXME someone figure out why this was.
6941    */
6942   if (!GTK_WIDGET_REALIZED (widget))
6943     {
6944       if (GTK_WIDGET_VISIBLE (widget))
6945         {
6946           GdkRectangle tmp_rectangle = widget->allocation;
6947           tmp_rectangle.x += scroll_data->dx;
6948           tmp_rectangle.y += scroll_data->dy;
6949           
6950           gtk_widget_size_allocate (widget, &tmp_rectangle);
6951         }
6952     }
6953   else
6954     {
6955       if (ALLOCATION_WINDOW (widget) == scroll_data->window)
6956         {
6957           widget->allocation.x += scroll_data->dx;
6958           widget->allocation.y += scroll_data->dy;
6959           
6960           if (GTK_IS_CONTAINER (widget))
6961             gtk_container_forall (GTK_CONTAINER (widget),
6962                                   adjust_allocation_recurse,
6963                                   data);
6964         }
6965     }
6966 }
6967
6968 static void
6969 adjust_allocation (GtkWidget *widget,
6970                    int        dx,
6971                    int        dy)
6972 {
6973   ScrollData scroll_data;
6974
6975   if (GTK_WIDGET_REALIZED (widget))
6976     scroll_data.window = ALLOCATION_WINDOW (widget);
6977   else
6978     scroll_data.window = NULL;
6979     
6980   scroll_data.dx = dx;
6981   scroll_data.dy = dy;
6982   
6983   adjust_allocation_recurse (widget, &scroll_data);
6984 }
6985             
6986 static void
6987 gtk_text_view_value_changed (GtkAdjustment *adj,
6988                              GtkTextView   *text_view)
6989 {
6990   GtkTextIter iter;
6991   gint line_top;
6992   gint dx = 0;
6993   gint dy = 0;
6994   
6995   /* Note that we oddly call this function with adj == NULL
6996    * sometimes
6997    */
6998   
6999   text_view->onscreen_validated = FALSE;
7000
7001   DV(g_print(">Scroll offset changed %s/%g, onscreen_validated = FALSE ("G_STRLOC")\n",
7002              adj == text_view->hadjustment ? "hadj" : adj == text_view->vadjustment ? "vadj" : "none",
7003              adj ? adj->value : 0.0));
7004   
7005   if (adj == text_view->hadjustment)
7006     {
7007       dx = text_view->xoffset - (gint)adj->value;
7008       text_view->xoffset = adj->value;
7009
7010       /* If the change is due to a size change we need 
7011        * to invalidate the entire text window because there might be
7012        * right-aligned or centered text 
7013        */
7014       if (text_view->width_changed)
7015         {
7016           if (GTK_WIDGET_REALIZED (text_view))
7017             gdk_window_invalidate_rect (text_view->text_window->bin_window, NULL, FALSE);
7018           
7019           text_view->width_changed = FALSE;
7020         }
7021     }
7022   else if (adj == text_view->vadjustment)
7023     {
7024       dy = text_view->yoffset - (gint)adj->value;
7025       text_view->yoffset = adj->value;
7026
7027       if (text_view->layout)
7028         {
7029           gtk_text_layout_get_line_at_y (text_view->layout, &iter, adj->value, &line_top);
7030
7031           gtk_text_buffer_move_mark (get_buffer (text_view), text_view->first_para_mark, &iter);
7032
7033           text_view->first_para_pixels = adj->value - line_top;
7034         }
7035     }
7036   
7037   if (dx != 0 || dy != 0)
7038     {
7039       GSList *tmp_list;
7040
7041       if (GTK_WIDGET_REALIZED (text_view))
7042         {
7043           if (dy != 0)
7044             {
7045               if (text_view->left_window)
7046                 text_window_scroll (text_view->left_window, 0, dy);
7047               if (text_view->right_window)
7048                 text_window_scroll (text_view->right_window, 0, dy);
7049             }
7050       
7051           if (dx != 0)
7052             {
7053               if (text_view->top_window)
7054                 text_window_scroll (text_view->top_window, dx, 0);
7055               if (text_view->bottom_window)
7056                 text_window_scroll (text_view->bottom_window, dx, 0);
7057             }
7058       
7059           /* It looks nicer to scroll the main area last, because
7060            * it takes a while, and making the side areas update
7061            * afterward emphasizes the slowness of scrolling the
7062            * main area.
7063            */
7064           text_window_scroll (text_view->text_window, dx, dy);
7065         }
7066       
7067       /* Children are now "moved" in the text window, poke
7068        * into widget->allocation for each child
7069        */
7070       tmp_list = text_view->children;
7071       while (tmp_list != NULL)
7072         {
7073           GtkTextViewChild *child = tmp_list->data;
7074           
7075           if (child->anchor)
7076             adjust_allocation (child->widget, dx, dy);
7077           
7078           tmp_list = g_slist_next (tmp_list);
7079         }
7080     }
7081
7082   /* This could result in invalidation, which would install the
7083    * first_validate_idle, which would validate onscreen;
7084    * but we're going to go ahead and validate here, so
7085    * first_validate_idle shouldn't have anything to do.
7086    */
7087   gtk_text_view_update_layout_width (text_view);
7088   
7089   /* note that validation of onscreen could invoke this function
7090    * recursively, by scrolling to maintain first_para, or in response
7091    * to updating the layout width, however there is no problem with
7092    * that, or shouldn't be.
7093    */
7094   gtk_text_view_validate_onscreen (text_view);
7095   
7096   /* process exposes */
7097   if (GTK_WIDGET_REALIZED (text_view))
7098     {
7099       DV (g_print ("Processing updates (%s)\n", G_STRLOC));
7100       
7101       if (text_view->left_window)
7102         gdk_window_process_updates (text_view->left_window->bin_window, TRUE);
7103
7104       if (text_view->right_window)
7105         gdk_window_process_updates (text_view->right_window->bin_window, TRUE);
7106
7107       if (text_view->top_window)
7108         gdk_window_process_updates (text_view->top_window->bin_window, TRUE);
7109       
7110       if (text_view->bottom_window)
7111         gdk_window_process_updates (text_view->bottom_window->bin_window, TRUE);
7112   
7113       gdk_window_process_updates (text_view->text_window->bin_window, TRUE);
7114     }
7115
7116   /* If this got installed, get rid of it, it's just a waste of time. */
7117   if (text_view->first_validate_idle != 0)
7118     {
7119       g_source_remove (text_view->first_validate_idle);
7120       text_view->first_validate_idle = 0;
7121     }
7122
7123   gtk_text_view_update_im_spot_location (text_view);
7124   
7125   DV(g_print(">End scroll offset changed handler ("G_STRLOC")\n"));
7126 }
7127
7128 static void
7129 gtk_text_view_commit_handler (GtkIMContext  *context,
7130                               const gchar   *str,
7131                               GtkTextView   *text_view)
7132 {
7133   gtk_text_view_commit_text (text_view, str);
7134 }
7135
7136 static void
7137 gtk_text_view_commit_text (GtkTextView   *text_view,
7138                            const gchar   *str)
7139 {
7140   gboolean had_selection;
7141   
7142   gtk_text_buffer_begin_user_action (get_buffer (text_view));
7143
7144   had_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
7145                                                         NULL, NULL);
7146   
7147   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
7148                                     text_view->editable);
7149
7150   if (!strcmp (str, "\n"))
7151     {
7152       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), "\n", 1,
7153                                                          text_view->editable))
7154         {
7155           gtk_widget_error_bell (GTK_WIDGET (text_view));
7156         }
7157     }
7158   else
7159     {
7160       if (!had_selection && text_view->overwrite_mode)
7161         {
7162           GtkTextIter insert;
7163           
7164           gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
7165                                             &insert,
7166                                             gtk_text_buffer_get_insert (get_buffer (text_view)));
7167           if (!gtk_text_iter_ends_line (&insert))
7168             gtk_text_view_delete_from_cursor (text_view, GTK_DELETE_CHARS, 1);
7169         }
7170
7171       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
7172                                                          text_view->editable))
7173         {
7174           gtk_widget_error_bell (GTK_WIDGET (text_view));
7175         }
7176     }
7177
7178   gtk_text_buffer_end_user_action (get_buffer (text_view));
7179
7180   gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
7181   DV(g_print (G_STRLOC": scrolling onscreen\n"));
7182   gtk_text_view_scroll_mark_onscreen (text_view,
7183                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
7184 }
7185
7186 static void
7187 gtk_text_view_preedit_changed_handler (GtkIMContext *context,
7188                                        GtkTextView  *text_view)
7189 {
7190   gchar *str;
7191   PangoAttrList *attrs;
7192   gint cursor_pos;
7193   GtkTextIter iter;
7194
7195   gtk_text_buffer_get_iter_at_mark (text_view->buffer, &iter, 
7196                                     gtk_text_buffer_get_insert (text_view->buffer));
7197
7198   /* Keypress events are passed to input method even if cursor position is not editable;
7199    * so beep here if it's multi-key input sequence, input method will be reset in 
7200    * key-press-event handler. */
7201   if (!gtk_text_iter_can_insert (&iter, text_view->editable))
7202     {
7203       gtk_widget_error_bell (GTK_WIDGET (text_view));
7204       return;
7205     }
7206
7207   gtk_im_context_get_preedit_string (context, &str, &attrs, &cursor_pos);
7208   gtk_text_layout_set_preedit_string (text_view->layout, str, attrs, cursor_pos);
7209   pango_attr_list_unref (attrs);
7210   g_free (str);
7211
7212   if (GTK_WIDGET_HAS_FOCUS (text_view))
7213     gtk_text_view_scroll_mark_onscreen (text_view,
7214                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
7215 }
7216
7217 static gboolean
7218 gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
7219                                             GtkTextView   *text_view)
7220 {
7221   GtkTextIter start;
7222   GtkTextIter end;
7223   gint pos;
7224   gchar *text;
7225
7226   gtk_text_buffer_get_iter_at_mark (text_view->buffer, &start,  
7227                                     gtk_text_buffer_get_insert (text_view->buffer));
7228   end = start;
7229
7230   pos = gtk_text_iter_get_line_index (&start);
7231   gtk_text_iter_set_line_offset (&start, 0);
7232   gtk_text_iter_forward_to_line_end (&end);
7233
7234   text = gtk_text_iter_get_slice (&start, &end);
7235   gtk_im_context_set_surrounding (context, text, -1, pos);
7236   g_free (text);
7237
7238   return TRUE;
7239 }
7240
7241 static gboolean
7242 gtk_text_view_delete_surrounding_handler (GtkIMContext  *context,
7243                                           gint           offset,
7244                                           gint           n_chars,
7245                                           GtkTextView   *text_view)
7246 {
7247   GtkTextIter start;
7248   GtkTextIter end;
7249
7250   gtk_text_buffer_get_iter_at_mark (text_view->buffer, &start,  
7251                                     gtk_text_buffer_get_insert (text_view->buffer));
7252   end = start;
7253
7254   gtk_text_iter_forward_chars (&start, offset);
7255   gtk_text_iter_forward_chars (&end, offset + n_chars);
7256
7257   gtk_text_buffer_delete_interactive (text_view->buffer, &start, &end,
7258                                       text_view->editable);
7259
7260   return TRUE;
7261 }
7262
7263 static void
7264 gtk_text_view_mark_set_handler (GtkTextBuffer     *buffer,
7265                                 const GtkTextIter *location,
7266                                 GtkTextMark       *mark,
7267                                 gpointer           data)
7268 {
7269   GtkTextView *text_view = GTK_TEXT_VIEW (data);
7270   gboolean need_reset = FALSE;
7271
7272   if (mark == gtk_text_buffer_get_insert (buffer))
7273     {
7274       text_view->virtual_cursor_x = -1;
7275       text_view->virtual_cursor_y = -1;
7276       gtk_text_view_update_im_spot_location (text_view);
7277       need_reset = TRUE;
7278     }
7279   else if (mark == gtk_text_buffer_get_selection_bound (buffer))
7280     {
7281       need_reset = TRUE;
7282     }
7283
7284   if (need_reset)
7285     gtk_text_view_reset_im_context (text_view);
7286 }
7287
7288 static void
7289 gtk_text_view_target_list_notify (GtkTextBuffer    *buffer,
7290                                   const GParamSpec *pspec,
7291                                   gpointer          data)
7292 {
7293   GtkWidget     *widget = GTK_WIDGET (data);
7294   GtkTargetList *view_list;
7295   GtkTargetList *buffer_list;
7296   GList         *list;
7297
7298   view_list = gtk_drag_dest_get_target_list (widget);
7299   buffer_list = gtk_text_buffer_get_paste_target_list (buffer);
7300
7301   if (view_list)
7302     gtk_target_list_ref (view_list);
7303   else
7304     view_list = gtk_target_list_new (NULL, 0);
7305
7306   list = view_list->list;
7307   while (list)
7308     {
7309       GtkTargetPair *pair = list->data;
7310
7311       list = g_list_next (list); /* get next element before removing */
7312
7313       if (pair->info >= GTK_TEXT_BUFFER_TARGET_INFO_TEXT &&
7314           pair->info <= GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
7315         {
7316           gtk_target_list_remove (view_list, pair->target);
7317         }
7318     }
7319
7320   for (list = buffer_list->list; list; list = g_list_next (list))
7321     {
7322       GtkTargetPair *pair = list->data;
7323
7324       gtk_target_list_add (view_list, pair->target, pair->flags, pair->info);
7325     }
7326
7327   gtk_drag_dest_set_target_list (widget, view_list);
7328   gtk_target_list_unref (view_list);
7329 }
7330
7331 static void
7332 gtk_text_view_get_cursor_location  (GtkTextView   *text_view,
7333                                     GdkRectangle  *pos)
7334 {
7335   GtkTextIter insert;
7336   
7337   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
7338                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
7339
7340   gtk_text_layout_get_cursor_locations (text_view->layout, &insert, pos, NULL);
7341 }
7342
7343 static void
7344 gtk_text_view_get_virtual_cursor_pos (GtkTextView *text_view,
7345                                       gint        *x,
7346                                       gint        *y)
7347 {
7348   GdkRectangle pos;
7349
7350   if ((x && text_view->virtual_cursor_x == -1) ||
7351       (y && text_view->virtual_cursor_y == -1))
7352     gtk_text_view_get_cursor_location (text_view, &pos);
7353
7354   if (x)
7355     {
7356       if (text_view->virtual_cursor_x != -1)
7357         *x = text_view->virtual_cursor_x;
7358       else
7359         *x = pos.x;
7360     }
7361
7362   if (y)
7363     {
7364       if (text_view->virtual_cursor_x != -1)
7365         *y = text_view->virtual_cursor_y;
7366       else
7367         *y = pos.y + pos.height / 2;
7368     }
7369 }
7370
7371 static void
7372 gtk_text_view_set_virtual_cursor_pos (GtkTextView *text_view,
7373                                       gint         x,
7374                                       gint         y)
7375 {
7376   GdkRectangle pos;
7377
7378   if (!text_view->layout)
7379     return;
7380
7381   if (x == -1 || y == -1)
7382     gtk_text_view_get_cursor_location (text_view, &pos);
7383
7384   text_view->virtual_cursor_x = (x == -1) ? pos.x : x;
7385   text_view->virtual_cursor_y = (y == -1) ? pos.y + pos.height / 2 : y;
7386 }
7387
7388 /* Quick hack of a popup menu
7389  */
7390 static void
7391 activate_cb (GtkWidget   *menuitem,
7392              GtkTextView *text_view)
7393 {
7394   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
7395   g_signal_emit_by_name (text_view, signal);
7396 }
7397
7398 static void
7399 append_action_signal (GtkTextView  *text_view,
7400                       GtkWidget    *menu,
7401                       const gchar  *stock_id,
7402                       const gchar  *signal,
7403                       gboolean      sensitive)
7404 {
7405   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
7406
7407   g_object_set_data (G_OBJECT (menuitem), I_("gtk-signal"), (char *)signal);
7408   g_signal_connect (menuitem, "activate",
7409                     G_CALLBACK (activate_cb), text_view);
7410
7411   gtk_widget_set_sensitive (menuitem, sensitive);
7412   
7413   gtk_widget_show (menuitem);
7414   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
7415 }
7416
7417 static void
7418 gtk_text_view_select_all (GtkWidget *widget,
7419                           gboolean select)
7420 {
7421   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
7422   GtkTextBuffer *buffer;
7423   GtkTextIter start_iter, end_iter, insert;
7424
7425   buffer = text_view->buffer;
7426   if (select) 
7427     {
7428       gtk_text_buffer_get_bounds (buffer, &start_iter, &end_iter);
7429       gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
7430     }
7431   else 
7432     {
7433       gtk_text_buffer_get_iter_at_mark (buffer, &insert,
7434                                         gtk_text_buffer_get_insert (buffer));
7435       gtk_text_buffer_move_mark_by_name (buffer, "selection_bound", &insert);
7436     }
7437 }
7438
7439 static void
7440 select_all_cb (GtkWidget   *menuitem,
7441                GtkTextView *text_view)
7442 {
7443   gtk_text_view_select_all (GTK_WIDGET (text_view), TRUE);
7444 }
7445
7446 static void
7447 delete_cb (GtkTextView *text_view)
7448 {
7449   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
7450                                     text_view->editable);
7451 }
7452
7453 static void
7454 popup_menu_detach (GtkWidget *attach_widget,
7455                    GtkMenu   *menu)
7456 {
7457   GTK_TEXT_VIEW (attach_widget)->popup_menu = NULL;
7458 }
7459
7460 static void
7461 popup_position_func (GtkMenu   *menu,
7462                      gint      *x,
7463                      gint      *y,
7464                      gboolean  *push_in,
7465                      gpointer   user_data)
7466 {
7467   GtkTextView *text_view;
7468   GtkWidget *widget;
7469   GdkRectangle cursor_rect;
7470   GdkRectangle onscreen_rect;
7471   gint root_x, root_y;
7472   GtkTextIter iter;
7473   GtkRequisition req;      
7474   GdkScreen *screen;
7475   gint monitor_num;
7476   GdkRectangle monitor;
7477       
7478   text_view = GTK_TEXT_VIEW (user_data);
7479   widget = GTK_WIDGET (text_view);
7480   
7481   g_return_if_fail (GTK_WIDGET_REALIZED (text_view));
7482   
7483   screen = gtk_widget_get_screen (widget);
7484
7485   gdk_window_get_origin (widget->window, &root_x, &root_y);
7486
7487   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
7488                                     &iter,
7489                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
7490
7491   gtk_text_view_get_iter_location (text_view,
7492                                    &iter,
7493                                    &cursor_rect);
7494
7495   gtk_text_view_get_visible_rect (text_view, &onscreen_rect);
7496   
7497   gtk_widget_size_request (text_view->popup_menu, &req);
7498
7499   /* can't use rectangle_intersect since cursor rect can have 0 width */
7500   if (cursor_rect.x >= onscreen_rect.x &&
7501       cursor_rect.x < onscreen_rect.x + onscreen_rect.width &&
7502       cursor_rect.y >= onscreen_rect.y &&
7503       cursor_rect.y < onscreen_rect.y + onscreen_rect.height)
7504     {    
7505       gtk_text_view_buffer_to_window_coords (text_view,
7506                                              GTK_TEXT_WINDOW_WIDGET,
7507                                              cursor_rect.x, cursor_rect.y,
7508                                              &cursor_rect.x, &cursor_rect.y);
7509
7510       *x = root_x + cursor_rect.x + cursor_rect.width;
7511       *y = root_y + cursor_rect.y + cursor_rect.height;
7512     }
7513   else
7514     {
7515       /* Just center the menu, since cursor is offscreen. */      
7516       *x = root_x + (widget->allocation.width / 2 - req.width / 2);
7517       *y = root_y + (widget->allocation.height / 2 - req.height / 2);      
7518     }
7519   
7520   /* Ensure sanity */
7521   *x = CLAMP (*x, root_x, (root_x + widget->allocation.width));
7522   *y = CLAMP (*y, root_y, (root_y + widget->allocation.height));
7523
7524   monitor_num = gdk_screen_get_monitor_at_point (screen, *x, *y);
7525   gtk_menu_set_monitor (menu, monitor_num);
7526   gdk_screen_get_monitor_geometry (screen, monitor_num, &monitor);
7527
7528   *x = CLAMP (*x, monitor.x, monitor.x + MAX (0, monitor.width - req.width));
7529   *y = CLAMP (*y, monitor.y, monitor.y + MAX (0, monitor.height - req.height));
7530
7531   *push_in = FALSE;
7532 }
7533
7534 typedef struct
7535 {
7536   GtkTextView *text_view;
7537   gint button;
7538   guint time;
7539 } PopupInfo;
7540
7541 static gboolean
7542 range_contains_editable_text (const GtkTextIter *start,
7543                               const GtkTextIter *end,
7544                               gboolean default_editability)
7545 {
7546   GtkTextIter iter = *start;
7547
7548   while (gtk_text_iter_compare (&iter, end) < 0)
7549     {
7550       if (gtk_text_iter_editable (&iter, default_editability))
7551         return TRUE;
7552       
7553       gtk_text_iter_forward_to_tag_toggle (&iter, NULL);
7554     }
7555
7556   return FALSE;
7557 }                             
7558
7559 static void
7560 unichar_chosen_func (const char *text,
7561                      gpointer    data)
7562 {
7563   GtkTextView *text_view = GTK_TEXT_VIEW (data);
7564
7565   gtk_text_view_commit_text (text_view, text);
7566 }
7567
7568 static void
7569 popup_targets_received (GtkClipboard     *clipboard,
7570                         GtkSelectionData *data,
7571                         gpointer          user_data)
7572 {
7573   PopupInfo *info = user_data;
7574   GtkTextView *text_view = info->text_view;
7575   
7576   if (GTK_WIDGET_REALIZED (text_view))
7577     {
7578       /* We implicitely rely here on the fact that if we are pasting ourself, we'll
7579        * have text targets as well as the private GTK_TEXT_BUFFER_CONTENTS target.
7580        */
7581       gboolean clipboard_contains_text;
7582       GtkWidget *menuitem;
7583       GtkWidget *submenu;
7584       gboolean have_selection;
7585       gboolean can_insert;
7586       GtkTextIter iter;
7587       GtkTextIter sel_start, sel_end;
7588       gboolean show_input_method_menu;
7589       gboolean show_unicode_menu;
7590       
7591       clipboard_contains_text = gtk_selection_data_targets_include_text (data);
7592
7593       if (text_view->popup_menu)
7594         gtk_widget_destroy (text_view->popup_menu);
7595
7596       text_view->popup_menu = gtk_menu_new ();
7597       
7598       gtk_menu_attach_to_widget (GTK_MENU (text_view->popup_menu),
7599                                  GTK_WIDGET (text_view),
7600                                  popup_menu_detach);
7601       
7602       have_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
7603                                                              &sel_start, &sel_end);
7604       
7605       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
7606                                         &iter,
7607                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
7608       
7609       can_insert = gtk_text_iter_can_insert (&iter, text_view->editable);
7610       
7611       append_action_signal (text_view, text_view->popup_menu, GTK_STOCK_CUT, "cut_clipboard",
7612                             have_selection &&
7613                             range_contains_editable_text (&sel_start, &sel_end,
7614                                                           text_view->editable));
7615       append_action_signal (text_view, text_view->popup_menu, GTK_STOCK_COPY, "copy_clipboard",
7616                             have_selection);
7617       append_action_signal (text_view, text_view->popup_menu, GTK_STOCK_PASTE, "paste_clipboard",
7618                             can_insert && clipboard_contains_text);
7619       
7620       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
7621       gtk_widget_set_sensitive (menuitem, 
7622                                 have_selection &&
7623                                 range_contains_editable_text (&sel_start, &sel_end,
7624                                                               text_view->editable));
7625       g_signal_connect_swapped (menuitem, "activate",
7626                                 G_CALLBACK (delete_cb), text_view);
7627       gtk_widget_show (menuitem);
7628       gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);
7629
7630       menuitem = gtk_separator_menu_item_new ();
7631       gtk_widget_show (menuitem);
7632       gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);
7633
7634       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_SELECT_ALL, NULL);
7635       g_signal_connect (menuitem, "activate",
7636                         G_CALLBACK (select_all_cb), text_view);
7637       gtk_widget_show (menuitem);
7638       gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);
7639
7640       g_object_get (gtk_widget_get_settings (GTK_WIDGET (text_view)),
7641                     "gtk-show-input-method-menu", &show_input_method_menu,
7642                     "gtk-show-unicode-menu", &show_unicode_menu,
7643                     NULL);
7644       
7645       if (show_input_method_menu || show_unicode_menu)
7646         {
7647           menuitem = gtk_separator_menu_item_new ();
7648           gtk_widget_show (menuitem);
7649           gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);
7650         }
7651
7652       if (show_input_method_menu)
7653         {
7654           menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
7655           gtk_widget_show (menuitem);
7656           gtk_widget_set_sensitive (menuitem, can_insert);
7657
7658           submenu = gtk_menu_new ();
7659           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
7660           gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);
7661           
7662           gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (text_view->im_context),
7663                                                 GTK_MENU_SHELL (submenu));
7664         }
7665
7666       if (show_unicode_menu)
7667         {
7668           menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode Control Character"));
7669           gtk_widget_show (menuitem);
7670           gtk_widget_set_sensitive (menuitem, can_insert);
7671       
7672           submenu = gtk_menu_new ();
7673           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
7674           gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);      
7675           
7676           _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
7677                                                         unichar_chosen_func,
7678                                                         text_view);
7679         }
7680           
7681       g_signal_emit (text_view,
7682                      signals[POPULATE_POPUP],
7683                      0,
7684                      text_view->popup_menu);
7685       
7686       if (info->button)
7687         gtk_menu_popup (GTK_MENU (text_view->popup_menu), NULL, NULL,
7688                         NULL, NULL,
7689                         info->button, info->time);
7690       else
7691         {
7692           gtk_menu_popup (GTK_MENU (text_view->popup_menu), NULL, NULL,
7693                           popup_position_func, text_view,
7694                           0, gtk_get_current_event_time ());
7695           gtk_menu_shell_select_first (GTK_MENU_SHELL (text_view->popup_menu), FALSE);
7696         }
7697     }
7698
7699   g_object_unref (text_view);
7700   g_free (info);
7701 }
7702
7703 static void
7704 gtk_text_view_do_popup (GtkTextView    *text_view,
7705                         GdkEventButton *event)
7706 {
7707   PopupInfo *info = g_new (PopupInfo, 1);
7708
7709   /* In order to know what entries we should make sensitive, we
7710    * ask for the current targets of the clipboard, and when
7711    * we get them, then we actually pop up the menu.
7712    */
7713   info->text_view = g_object_ref (text_view);
7714   
7715   if (event)
7716     {
7717       info->button = event->button;
7718       info->time = event->time;
7719     }
7720   else
7721     {
7722       info->button = 0;
7723       info->time = gtk_get_current_event_time ();
7724     }
7725
7726   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (text_view),
7727                                                             GDK_SELECTION_CLIPBOARD),
7728                                   gdk_atom_intern_static_string ("TARGETS"),
7729                                   popup_targets_received,
7730                                   info);
7731 }
7732
7733 static gboolean
7734 gtk_text_view_popup_menu (GtkWidget *widget)
7735 {
7736   gtk_text_view_do_popup (GTK_TEXT_VIEW (widget), NULL);  
7737   return TRUE;
7738 }
7739
7740 /* Child GdkWindows */
7741
7742
7743 static GtkTextWindow*
7744 text_window_new (GtkTextWindowType  type,
7745                  GtkWidget         *widget,
7746                  gint               width_request,
7747                  gint               height_request)
7748 {
7749   GtkTextWindow *win;
7750
7751   win = g_new (GtkTextWindow, 1);
7752
7753   win->type = type;
7754   win->widget = widget;
7755   win->window = NULL;
7756   win->bin_window = NULL;
7757   win->requisition.width = width_request;
7758   win->requisition.height = height_request;
7759   win->allocation.width = width_request;
7760   win->allocation.height = height_request;
7761   win->allocation.x = 0;
7762   win->allocation.y = 0;
7763
7764   return win;
7765 }
7766
7767 static void
7768 text_window_free (GtkTextWindow *win)
7769 {
7770   if (win->window)
7771     text_window_unrealize (win);
7772
7773   g_free (win);
7774 }
7775
7776 static void
7777 text_window_realize (GtkTextWindow *win,
7778                      GtkWidget     *widget)
7779 {
7780   GdkWindowAttr attributes;
7781   gint attributes_mask;
7782   GdkCursor *cursor;
7783
7784   attributes.window_type = GDK_WINDOW_CHILD;
7785   attributes.x = win->allocation.x;
7786   attributes.y = win->allocation.y;
7787   attributes.width = win->allocation.width;
7788   attributes.height = win->allocation.height;
7789   attributes.wclass = GDK_INPUT_OUTPUT;
7790   attributes.visual = gtk_widget_get_visual (win->widget);
7791   attributes.colormap = gtk_widget_get_colormap (win->widget);
7792   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK;
7793
7794   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
7795
7796   win->window = gdk_window_new (widget->window,
7797                                 &attributes,
7798                                 attributes_mask);
7799
7800   gdk_window_set_back_pixmap (win->window, NULL, FALSE);
7801   
7802   gdk_window_show (win->window);
7803   gdk_window_set_user_data (win->window, win->widget);
7804   gdk_window_lower (win->window);
7805
7806   attributes.x = 0;
7807   attributes.y = 0;
7808   attributes.width = win->allocation.width;
7809   attributes.height = win->allocation.height;
7810   attributes.event_mask = (GDK_EXPOSURE_MASK            |
7811                            GDK_SCROLL_MASK              |
7812                            GDK_KEY_PRESS_MASK           |
7813                            GDK_BUTTON_PRESS_MASK        |
7814                            GDK_BUTTON_RELEASE_MASK      |
7815                            GDK_POINTER_MOTION_MASK      |
7816                            GDK_POINTER_MOTION_HINT_MASK |
7817                            gtk_widget_get_events (win->widget));
7818
7819   win->bin_window = gdk_window_new (win->window,
7820                                     &attributes,
7821                                     attributes_mask);
7822
7823   gdk_window_show (win->bin_window);
7824   gdk_window_set_user_data (win->bin_window, win->widget);
7825
7826   if (win->type == GTK_TEXT_WINDOW_TEXT)
7827     {
7828       if (GTK_WIDGET_IS_SENSITIVE (widget))
7829         {
7830           /* I-beam cursor */
7831           cursor = gdk_cursor_new_for_display (gdk_drawable_get_display (widget->window),
7832                                                GDK_XTERM);
7833           gdk_window_set_cursor (win->bin_window, cursor);
7834           gdk_cursor_unref (cursor);
7835         } 
7836
7837       gtk_im_context_set_client_window (GTK_TEXT_VIEW (widget)->im_context,
7838                                         win->window);
7839
7840
7841       gdk_window_set_background (win->bin_window,
7842                                  &widget->style->base[GTK_WIDGET_STATE (widget)]);
7843     }
7844   else
7845     {
7846       gdk_window_set_background (win->bin_window,
7847                                  &widget->style->bg[GTK_WIDGET_STATE (widget)]);
7848     }
7849
7850   g_object_set_qdata (G_OBJECT (win->window),
7851                       g_quark_from_static_string ("gtk-text-view-text-window"),
7852                       win);
7853
7854   g_object_set_qdata (G_OBJECT (win->bin_window),
7855                       g_quark_from_static_string ("gtk-text-view-text-window"),
7856                       win);
7857 }
7858
7859 static void
7860 text_window_unrealize (GtkTextWindow *win)
7861 {
7862   if (win->type == GTK_TEXT_WINDOW_TEXT)
7863     {
7864       gtk_im_context_set_client_window (GTK_TEXT_VIEW (win->widget)->im_context,
7865                                         NULL);
7866     }
7867
7868   gdk_window_set_user_data (win->window, NULL);
7869   gdk_window_set_user_data (win->bin_window, NULL);
7870   gdk_window_destroy (win->bin_window);
7871   gdk_window_destroy (win->window);
7872   win->window = NULL;
7873   win->bin_window = NULL;
7874 }
7875
7876 static void
7877 text_window_size_allocate (GtkTextWindow *win,
7878                            GdkRectangle  *rect)
7879 {
7880   win->allocation = *rect;
7881
7882   if (win->window)
7883     {
7884       gdk_window_move_resize (win->window,
7885                               rect->x, rect->y,
7886                               rect->width, rect->height);
7887
7888       gdk_window_resize (win->bin_window,
7889                          rect->width, rect->height);
7890     }
7891 }
7892
7893 static void
7894 text_window_scroll        (GtkTextWindow *win,
7895                            gint           dx,
7896                            gint           dy)
7897 {
7898   if (dx != 0 || dy != 0)
7899     {
7900       gdk_window_scroll (win->bin_window, dx, dy);
7901     }
7902 }
7903
7904 static void
7905 text_window_invalidate_rect (GtkTextWindow *win,
7906                              GdkRectangle  *rect)
7907 {
7908   GdkRectangle window_rect;
7909
7910   gtk_text_view_buffer_to_window_coords (GTK_TEXT_VIEW (win->widget),
7911                                          win->type,
7912                                          rect->x,
7913                                          rect->y,
7914                                          &window_rect.x,
7915                                          &window_rect.y);
7916
7917   window_rect.width = rect->width;
7918   window_rect.height = rect->height;
7919   
7920   /* Adjust the rect as appropriate */
7921   
7922   switch (win->type)
7923     {
7924     case GTK_TEXT_WINDOW_TEXT:
7925       break;
7926
7927     case GTK_TEXT_WINDOW_LEFT:
7928     case GTK_TEXT_WINDOW_RIGHT:
7929       window_rect.x = 0;
7930       window_rect.width = win->allocation.width;
7931       break;
7932
7933     case GTK_TEXT_WINDOW_TOP:
7934     case GTK_TEXT_WINDOW_BOTTOM:
7935       window_rect.y = 0;
7936       window_rect.height = win->allocation.height;
7937       break;
7938
7939     default:
7940       g_warning ("%s: bug!", G_STRFUNC);
7941       return;
7942       break;
7943     }
7944           
7945   gdk_window_invalidate_rect (win->bin_window, &window_rect, FALSE);
7946
7947 #if 0
7948   {
7949     cairo_t *cr = gdk_cairo_create (win->bin_window);
7950     gdk_cairo_rectangle (cr, &window_rect);
7951     cairo_set_source_rgb  (cr, 1.0, 0.0, 0.0);  /* red */
7952     cairo_fill (cr);
7953     cairo_destroy (cr);
7954   }
7955 #endif
7956 }
7957
7958 static void
7959 text_window_invalidate_cursors (GtkTextWindow *win)
7960 {
7961   GtkTextView *text_view = GTK_TEXT_VIEW (win->widget);
7962   GtkTextIter  iter;
7963   GdkRectangle strong;
7964   GdkRectangle weak;
7965   gboolean     draw_arrow;
7966   gfloat       cursor_aspect_ratio;
7967   gint         stem_width;
7968   gint         arrow_width;
7969
7970   gtk_text_buffer_get_iter_at_mark (text_view->buffer, &iter,
7971                                     gtk_text_buffer_get_insert (text_view->buffer));
7972
7973   if (_gtk_text_layout_get_block_cursor (text_view->layout, &strong))
7974     {
7975       text_window_invalidate_rect (win, &strong);
7976       return;
7977     }
7978
7979   gtk_text_layout_get_cursor_locations (text_view->layout, &iter,
7980                                         &strong, &weak);
7981
7982   /* cursor width calculation as in gtkstyle.c:draw_insertion_cursor(),
7983    * ignoring the text direction be exposing both sides of the cursor
7984    */
7985
7986   draw_arrow = (strong.x != weak.x || strong.y != weak.y);
7987
7988   gtk_widget_style_get (win->widget,
7989                         "cursor-aspect-ratio", &cursor_aspect_ratio,
7990                         NULL);
7991   
7992   stem_width = strong.height * cursor_aspect_ratio + 1;
7993   arrow_width = stem_width + 1;
7994
7995   strong.width = stem_width;
7996
7997   /* round up to the next even number */
7998   if (stem_width & 1)
7999     stem_width++;
8000
8001   strong.x     -= stem_width / 2;
8002   strong.width += stem_width;
8003
8004   if (draw_arrow)
8005     {
8006       strong.x     -= arrow_width;
8007       strong.width += arrow_width * 2;
8008     }
8009
8010   text_window_invalidate_rect (win, &strong);
8011
8012   if (draw_arrow) /* == have weak */
8013     {
8014       stem_width = weak.height * cursor_aspect_ratio + 1;
8015       arrow_width = stem_width + 1;
8016
8017       weak.width = stem_width;
8018
8019       /* round up to the next even number */
8020       if (stem_width & 1)
8021         stem_width++;
8022
8023       weak.x     -= stem_width / 2;
8024       weak.width += stem_width;
8025
8026       weak.x     -= arrow_width;
8027       weak.width += arrow_width * 2;
8028
8029       text_window_invalidate_rect (win, &weak);
8030     }
8031 }
8032
8033 static gint
8034 text_window_get_width (GtkTextWindow *win)
8035 {
8036   return win->allocation.width;
8037 }
8038
8039 static gint
8040 text_window_get_height (GtkTextWindow *win)
8041 {
8042   return win->allocation.height;
8043 }
8044
8045 /* Windows */
8046
8047
8048 /**
8049  * gtk_text_view_get_window:
8050  * @text_view: a #GtkTextView
8051  * @win: window to get
8052  *
8053  * Retrieves the #GdkWindow corresponding to an area of the text view;
8054  * possible windows include the overall widget window, child windows
8055  * on the left, right, top, bottom, and the window that displays the
8056  * text buffer. Windows are %NULL and nonexistent if their width or
8057  * height is 0, and are nonexistent before the widget has been
8058  * realized.
8059  *
8060  * Return value: a #GdkWindow, or %NULL
8061  **/
8062 GdkWindow*
8063 gtk_text_view_get_window (GtkTextView *text_view,
8064                           GtkTextWindowType win)
8065 {
8066   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
8067
8068   switch (win)
8069     {
8070     case GTK_TEXT_WINDOW_WIDGET:
8071       return GTK_WIDGET (text_view)->window;
8072       break;
8073
8074     case GTK_TEXT_WINDOW_TEXT:
8075       return text_view->text_window->bin_window;
8076       break;
8077
8078     case GTK_TEXT_WINDOW_LEFT:
8079       if (text_view->left_window)
8080         return text_view->left_window->bin_window;
8081       else
8082         return NULL;
8083       break;
8084
8085     case GTK_TEXT_WINDOW_RIGHT:
8086       if (text_view->right_window)
8087         return text_view->right_window->bin_window;
8088       else
8089         return NULL;
8090       break;
8091
8092     case GTK_TEXT_WINDOW_TOP:
8093       if (text_view->top_window)
8094         return text_view->top_window->bin_window;
8095       else
8096         return NULL;
8097       break;
8098
8099     case GTK_TEXT_WINDOW_BOTTOM:
8100       if (text_view->bottom_window)
8101         return text_view->bottom_window->bin_window;
8102       else
8103         return NULL;
8104       break;
8105
8106     case GTK_TEXT_WINDOW_PRIVATE:
8107       g_warning ("%s: You can't get GTK_TEXT_WINDOW_PRIVATE, it has \"PRIVATE\" in the name because it is private.", G_STRFUNC);
8108       return NULL;
8109       break;
8110     }
8111
8112   g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
8113   return NULL;
8114 }
8115
8116 /**
8117  * gtk_text_view_get_window_type:
8118  * @text_view: a #GtkTextView
8119  * @window: a window type
8120  *
8121  * Usually used to find out which window an event corresponds to.
8122  * If you connect to an event signal on @text_view, this function
8123  * should be called on <literal>event-&gt;window</literal> to
8124  * see which window it was.
8125  *
8126  * Return value: the window type.
8127  **/
8128 GtkTextWindowType
8129 gtk_text_view_get_window_type (GtkTextView *text_view,
8130                                GdkWindow   *window)
8131 {
8132   GtkTextWindow *win;
8133
8134   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
8135   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
8136
8137   if (window == GTK_WIDGET (text_view)->window)
8138     return GTK_TEXT_WINDOW_WIDGET;
8139
8140   win = g_object_get_qdata (G_OBJECT (window),
8141                             g_quark_try_string ("gtk-text-view-text-window"));
8142
8143   if (win)
8144     return win->type;
8145   else
8146     {
8147       return GTK_TEXT_WINDOW_PRIVATE;
8148     }
8149 }
8150
8151 static void
8152 buffer_to_widget (GtkTextView      *text_view,
8153                   gint              buffer_x,
8154                   gint              buffer_y,
8155                   gint             *window_x,
8156                   gint             *window_y)
8157 {  
8158   if (window_x)
8159     {
8160       *window_x = buffer_x - text_view->xoffset;
8161       *window_x += text_view->text_window->allocation.x;
8162     }
8163
8164   if (window_y)
8165     {
8166       *window_y = buffer_y - text_view->yoffset;
8167       *window_y += text_view->text_window->allocation.y;
8168     }
8169 }
8170
8171 static void
8172 widget_to_text_window (GtkTextWindow *win,
8173                        gint           widget_x,
8174                        gint           widget_y,
8175                        gint          *window_x,
8176                        gint          *window_y)
8177 {
8178   if (window_x)
8179     *window_x = widget_x - win->allocation.x;
8180
8181   if (window_y)
8182     *window_y = widget_y - win->allocation.y;
8183 }
8184
8185 static void
8186 buffer_to_text_window (GtkTextView   *text_view,
8187                        GtkTextWindow *win,
8188                        gint           buffer_x,
8189                        gint           buffer_y,
8190                        gint          *window_x,
8191                        gint          *window_y)
8192 {
8193   if (win == NULL)
8194     {
8195       g_warning ("Attempt to convert text buffer coordinates to coordinates "
8196                  "for a nonexistent or private child window of GtkTextView");
8197       return;
8198     }
8199
8200   buffer_to_widget (text_view,
8201                     buffer_x, buffer_y,
8202                     window_x, window_y);
8203
8204   widget_to_text_window (win,
8205                          window_x ? *window_x : 0,
8206                          window_y ? *window_y : 0,
8207                          window_x,
8208                          window_y);
8209 }
8210
8211 /**
8212  * gtk_text_view_buffer_to_window_coords:
8213  * @text_view: a #GtkTextView
8214  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
8215  * @buffer_x: buffer x coordinate
8216  * @buffer_y: buffer y coordinate
8217  * @window_x: window x coordinate return location
8218  * @window_y: window y coordinate return location
8219  *
8220  * Converts coordinate (@buffer_x, @buffer_y) to coordinates for the window
8221  * @win, and stores the result in (@window_x, @window_y). 
8222  *
8223  * Note that you can't convert coordinates for a nonexisting window (see 
8224  * gtk_text_view_set_border_window_size()).
8225  **/
8226 void
8227 gtk_text_view_buffer_to_window_coords (GtkTextView      *text_view,
8228                                        GtkTextWindowType win,
8229                                        gint              buffer_x,
8230                                        gint              buffer_y,
8231                                        gint             *window_x,
8232                                        gint             *window_y)
8233 {
8234   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
8235
8236   switch (win)
8237     {
8238     case GTK_TEXT_WINDOW_WIDGET:
8239       buffer_to_widget (text_view,
8240                         buffer_x, buffer_y,
8241                         window_x, window_y);
8242       break;
8243
8244     case GTK_TEXT_WINDOW_TEXT:
8245       if (window_x)
8246         *window_x = buffer_x - text_view->xoffset;
8247       if (window_y)
8248         *window_y = buffer_y - text_view->yoffset;
8249       break;
8250
8251     case GTK_TEXT_WINDOW_LEFT:
8252       buffer_to_text_window (text_view,
8253                              text_view->left_window,
8254                              buffer_x, buffer_y,
8255                              window_x, window_y);
8256       break;
8257
8258     case GTK_TEXT_WINDOW_RIGHT:
8259       buffer_to_text_window (text_view,
8260                              text_view->right_window,
8261                              buffer_x, buffer_y,
8262                              window_x, window_y);
8263       break;
8264
8265     case GTK_TEXT_WINDOW_TOP:
8266       buffer_to_text_window (text_view,
8267                              text_view->top_window,
8268                              buffer_x, buffer_y,
8269                              window_x, window_y);
8270       break;
8271
8272     case GTK_TEXT_WINDOW_BOTTOM:
8273       buffer_to_text_window (text_view,
8274                              text_view->bottom_window,
8275                              buffer_x, buffer_y,
8276                              window_x, window_y);
8277       break;
8278
8279     case GTK_TEXT_WINDOW_PRIVATE:
8280       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
8281       break;
8282
8283     default:
8284       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
8285       break;
8286     }
8287 }
8288
8289 static void
8290 widget_to_buffer (GtkTextView *text_view,
8291                   gint         widget_x,
8292                   gint         widget_y,
8293                   gint        *buffer_x,
8294                   gint        *buffer_y)
8295 {  
8296   if (buffer_x)
8297     {
8298       *buffer_x = widget_x + text_view->xoffset;
8299       *buffer_x -= text_view->text_window->allocation.x;
8300     }
8301
8302   if (buffer_y)
8303     {
8304       *buffer_y = widget_y + text_view->yoffset;
8305       *buffer_y -= text_view->text_window->allocation.y;
8306     }
8307 }
8308
8309 static void
8310 text_window_to_widget (GtkTextWindow *win,
8311                        gint           window_x,
8312                        gint           window_y,
8313                        gint          *widget_x,
8314                        gint          *widget_y)
8315 {
8316   if (widget_x)
8317     *widget_x = window_x + win->allocation.x;
8318
8319   if (widget_y)
8320     *widget_y = window_y + win->allocation.y;
8321 }
8322
8323 static void
8324 text_window_to_buffer (GtkTextView   *text_view,
8325                        GtkTextWindow *win,
8326                        gint           window_x,
8327                        gint           window_y,
8328                        gint          *buffer_x,
8329                        gint          *buffer_y)
8330 {
8331   if (win == NULL)
8332     {
8333       g_warning ("Attempt to convert GtkTextView buffer coordinates into "
8334                  "coordinates for a nonexistent child window.");
8335       return;
8336     }
8337
8338   text_window_to_widget (win,
8339                          window_x,
8340                          window_y,
8341                          buffer_x,
8342                          buffer_y);
8343
8344   widget_to_buffer (text_view,
8345                     buffer_x ? *buffer_x : 0,
8346                     buffer_y ? *buffer_y : 0,
8347                     buffer_x,
8348                     buffer_y);
8349 }
8350
8351 /**
8352  * gtk_text_view_window_to_buffer_coords:
8353  * @text_view: a #GtkTextView
8354  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
8355  * @window_x: window x coordinate
8356  * @window_y: window y coordinate
8357  * @buffer_x: buffer x coordinate return location
8358  * @buffer_y: buffer y coordinate return location
8359  *
8360  * Converts coordinates on the window identified by @win to buffer
8361  * coordinates, storing the result in (@buffer_x,@buffer_y).
8362  *
8363  * Note that you can't convert coordinates for a nonexisting window (see 
8364  * gtk_text_view_set_border_window_size()).
8365  **/
8366 void
8367 gtk_text_view_window_to_buffer_coords (GtkTextView      *text_view,
8368                                        GtkTextWindowType win,
8369                                        gint              window_x,
8370                                        gint              window_y,
8371                                        gint             *buffer_x,
8372                                        gint             *buffer_y)
8373 {
8374   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
8375
8376   switch (win)
8377     {
8378     case GTK_TEXT_WINDOW_WIDGET:
8379       widget_to_buffer (text_view,
8380                         window_x, window_y,
8381                         buffer_x, buffer_y);
8382       break;
8383
8384     case GTK_TEXT_WINDOW_TEXT:
8385       if (buffer_x)
8386         *buffer_x = window_x + text_view->xoffset;
8387       if (buffer_y)
8388         *buffer_y = window_y + text_view->yoffset;
8389       break;
8390
8391     case GTK_TEXT_WINDOW_LEFT:
8392       text_window_to_buffer (text_view,
8393                              text_view->left_window,
8394                              window_x, window_y,
8395                              buffer_x, buffer_y);
8396       break;
8397
8398     case GTK_TEXT_WINDOW_RIGHT:
8399       text_window_to_buffer (text_view,
8400                              text_view->right_window,
8401                              window_x, window_y,
8402                              buffer_x, buffer_y);
8403       break;
8404
8405     case GTK_TEXT_WINDOW_TOP:
8406       text_window_to_buffer (text_view,
8407                              text_view->top_window,
8408                              window_x, window_y,
8409                              buffer_x, buffer_y);
8410       break;
8411
8412     case GTK_TEXT_WINDOW_BOTTOM:
8413       text_window_to_buffer (text_view,
8414                              text_view->bottom_window,
8415                              window_x, window_y,
8416                              buffer_x, buffer_y);
8417       break;
8418
8419     case GTK_TEXT_WINDOW_PRIVATE:
8420       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
8421       break;
8422
8423     default:
8424       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
8425       break;
8426     }
8427 }
8428
8429 static void
8430 set_window_width (GtkTextView      *text_view,
8431                   gint              width,
8432                   GtkTextWindowType type,
8433                   GtkTextWindow   **winp)
8434 {
8435   if (width == 0)
8436     {
8437       if (*winp)
8438         {
8439           text_window_free (*winp);
8440           *winp = NULL;
8441           gtk_widget_queue_resize (GTK_WIDGET (text_view));
8442         }
8443     }
8444   else
8445     {
8446       if (*winp == NULL)
8447         {
8448           *winp = text_window_new (type,
8449                                    GTK_WIDGET (text_view),
8450                                    width, 0);
8451           /* if the widget is already realized we need to realize the child manually */
8452           if (GTK_WIDGET_REALIZED (text_view))
8453             text_window_realize (*winp, GTK_WIDGET (text_view));
8454         }
8455       else
8456         {
8457           if ((*winp)->requisition.width == width)
8458             return;
8459
8460           (*winp)->requisition.width = width;
8461         }
8462
8463       gtk_widget_queue_resize (GTK_WIDGET (text_view));
8464     }
8465 }
8466
8467
8468 static void
8469 set_window_height (GtkTextView      *text_view,
8470                    gint              height,
8471                    GtkTextWindowType type,
8472                    GtkTextWindow   **winp)
8473 {
8474   if (height == 0)
8475     {
8476       if (*winp)
8477         {
8478           text_window_free (*winp);
8479           *winp = NULL;
8480           gtk_widget_queue_resize (GTK_WIDGET (text_view));
8481         }
8482     }
8483   else
8484     {
8485       if (*winp == NULL)
8486         {
8487           *winp = text_window_new (type,
8488                                    GTK_WIDGET (text_view),
8489                                    0, height);
8490
8491           /* if the widget is already realized we need to realize the child manually */
8492           if (GTK_WIDGET_REALIZED (text_view))
8493             text_window_realize (*winp, GTK_WIDGET (text_view));
8494         }
8495       else
8496         {
8497           if ((*winp)->requisition.height == height)
8498             return;
8499
8500           (*winp)->requisition.height = height;
8501         }
8502
8503       gtk_widget_queue_resize (GTK_WIDGET (text_view));
8504     }
8505 }
8506
8507 /**
8508  * gtk_text_view_set_border_window_size:
8509  * @text_view: a #GtkTextView
8510  * @type: window to affect
8511  * @size: width or height of the window
8512  *
8513  * Sets the width of %GTK_TEXT_WINDOW_LEFT or %GTK_TEXT_WINDOW_RIGHT,
8514  * or the height of %GTK_TEXT_WINDOW_TOP or %GTK_TEXT_WINDOW_BOTTOM.
8515  * Automatically destroys the corresponding window if the size is set
8516  * to 0, and creates the window if the size is set to non-zero.  This
8517  * function can only be used for the "border windows," it doesn't work
8518  * with #GTK_TEXT_WINDOW_WIDGET, #GTK_TEXT_WINDOW_TEXT, or
8519  * #GTK_TEXT_WINDOW_PRIVATE.
8520  **/
8521 void
8522 gtk_text_view_set_border_window_size (GtkTextView      *text_view,
8523                                       GtkTextWindowType type,
8524                                       gint              size)
8525
8526 {
8527   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
8528   g_return_if_fail (size >= 0);
8529
8530   switch (type)
8531     {
8532     case GTK_TEXT_WINDOW_LEFT:
8533       set_window_width (text_view, size, GTK_TEXT_WINDOW_LEFT,
8534                         &text_view->left_window);
8535       break;
8536
8537     case GTK_TEXT_WINDOW_RIGHT:
8538       set_window_width (text_view, size, GTK_TEXT_WINDOW_RIGHT,
8539                         &text_view->right_window);
8540       break;
8541
8542     case GTK_TEXT_WINDOW_TOP:
8543       set_window_height (text_view, size, GTK_TEXT_WINDOW_TOP,
8544                          &text_view->top_window);
8545       break;
8546
8547     case GTK_TEXT_WINDOW_BOTTOM:
8548       set_window_height (text_view, size, GTK_TEXT_WINDOW_BOTTOM,
8549                          &text_view->bottom_window);
8550       break;
8551
8552     default:
8553       g_warning ("Can only set size of left/right/top/bottom border windows with gtk_text_view_set_border_window_size()");
8554       break;
8555     }
8556 }
8557
8558 /**
8559  * gtk_text_view_get_border_window_size:
8560  * @text_view: a #GtkTextView
8561  * @type: window to return size from
8562  *
8563  * Gets the width of the specified border window. See
8564  * gtk_text_view_set_border_window_size().
8565  *
8566  * Return value: width of window
8567  **/
8568 gint
8569 gtk_text_view_get_border_window_size (GtkTextView       *text_view,
8570                                       GtkTextWindowType  type)
8571 {
8572   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
8573   
8574   switch (type)
8575     {
8576     case GTK_TEXT_WINDOW_LEFT:
8577       if (text_view->left_window)
8578         return text_view->left_window->requisition.width;
8579       break;
8580       
8581     case GTK_TEXT_WINDOW_RIGHT:
8582       if (text_view->right_window)
8583         return text_view->right_window->requisition.width;
8584       break;
8585       
8586     case GTK_TEXT_WINDOW_TOP:
8587       if (text_view->top_window)
8588         return text_view->top_window->requisition.height;
8589       break;
8590
8591     case GTK_TEXT_WINDOW_BOTTOM:
8592       if (text_view->bottom_window)
8593         return text_view->bottom_window->requisition.height;
8594       break;
8595       
8596     default:
8597       g_warning ("Can only get size of left/right/top/bottom border windows with gtk_text_view_get_border_window_size()");
8598       break;
8599     }
8600
8601   return 0;
8602 }
8603
8604 /*
8605  * Child widgets
8606  */
8607
8608 static GtkTextViewChild*
8609 text_view_child_new_anchored (GtkWidget          *child,
8610                               GtkTextChildAnchor *anchor,
8611                               GtkTextLayout      *layout)
8612 {
8613   GtkTextViewChild *vc;
8614
8615   vc = g_new (GtkTextViewChild, 1);
8616
8617   vc->type = GTK_TEXT_WINDOW_PRIVATE;
8618   vc->widget = child;
8619   vc->anchor = anchor;
8620
8621   vc->from_top_of_line = 0;
8622   vc->from_left_of_buffer = 0;
8623   
8624   g_object_ref (vc->widget);
8625   g_object_ref (vc->anchor);
8626
8627   g_object_set_data (G_OBJECT (child),
8628                      I_("gtk-text-view-child"),
8629                      vc);
8630
8631   gtk_text_child_anchor_register_child (anchor, child, layout);
8632   
8633   return vc;
8634 }
8635
8636 static GtkTextViewChild*
8637 text_view_child_new_window (GtkWidget          *child,
8638                             GtkTextWindowType   type,
8639                             gint                x,
8640                             gint                y)
8641 {
8642   GtkTextViewChild *vc;
8643
8644   vc = g_new (GtkTextViewChild, 1);
8645
8646   vc->widget = child;
8647   vc->anchor = NULL;
8648
8649   vc->from_top_of_line = 0;
8650   vc->from_left_of_buffer = 0;
8651  
8652   g_object_ref (vc->widget);
8653
8654   vc->type = type;
8655   vc->x = x;
8656   vc->y = y;
8657
8658   g_object_set_data (G_OBJECT (child),
8659                      I_("gtk-text-view-child"),
8660                      vc);
8661   
8662   return vc;
8663 }
8664
8665 static void
8666 text_view_child_free (GtkTextViewChild *child)
8667 {
8668   g_object_set_data (G_OBJECT (child->widget),
8669                      I_("gtk-text-view-child"), NULL);
8670
8671   if (child->anchor)
8672     {
8673       gtk_text_child_anchor_unregister_child (child->anchor,
8674                                               child->widget);
8675       g_object_unref (child->anchor);
8676     }
8677
8678   g_object_unref (child->widget);
8679
8680   g_free (child);
8681 }
8682
8683 static void
8684 text_view_child_set_parent_window (GtkTextView      *text_view,
8685                                    GtkTextViewChild *vc)
8686 {
8687   if (vc->anchor)
8688     gtk_widget_set_parent_window (vc->widget,
8689                                   text_view->text_window->bin_window);
8690   else
8691     {
8692       GdkWindow *window;
8693       window = gtk_text_view_get_window (text_view,
8694                                          vc->type);
8695       gtk_widget_set_parent_window (vc->widget, window);
8696     }
8697 }
8698
8699 static void
8700 add_child (GtkTextView      *text_view,
8701            GtkTextViewChild *vc)
8702 {
8703   text_view->children = g_slist_prepend (text_view->children,
8704                                          vc);
8705
8706   if (GTK_WIDGET_REALIZED (text_view))
8707     text_view_child_set_parent_window (text_view, vc);
8708   
8709   gtk_widget_set_parent (vc->widget, GTK_WIDGET (text_view));
8710 }
8711
8712 /**
8713  * gtk_text_view_add_child_at_anchor:
8714  * @text_view: a #GtkTextView
8715  * @child: a #GtkWidget
8716  * @anchor: a #GtkTextChildAnchor in the #GtkTextBuffer for @text_view
8717  * 
8718  * Adds a child widget in the text buffer, at the given @anchor.
8719  **/
8720 void
8721 gtk_text_view_add_child_at_anchor (GtkTextView          *text_view,
8722                                    GtkWidget            *child,
8723                                    GtkTextChildAnchor   *anchor)
8724 {
8725   GtkTextViewChild *vc;
8726
8727   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
8728   g_return_if_fail (GTK_IS_WIDGET (child));
8729   g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
8730   g_return_if_fail (child->parent == NULL);
8731
8732   gtk_text_view_ensure_layout (text_view);
8733
8734   vc = text_view_child_new_anchored (child, anchor,
8735                                      text_view->layout);
8736
8737   add_child (text_view, vc);
8738
8739   g_assert (vc->widget == child);
8740   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
8741 }
8742
8743 /**
8744  * gtk_text_view_add_child_in_window:
8745  * @text_view: a #GtkTextView
8746  * @child: a #GtkWidget
8747  * @which_window: which window the child should appear in
8748  * @xpos: X position of child in window coordinates
8749  * @ypos: Y position of child in window coordinates
8750  *
8751  * Adds a child at fixed coordinates in one of the text widget's
8752  * windows. The window must have nonzero size (see
8753  * gtk_text_view_set_border_window_size()). Note that the child
8754  * coordinates are given relative to the #GdkWindow in question, and
8755  * that these coordinates have no sane relationship to scrolling. When
8756  * placing a child in #GTK_TEXT_WINDOW_WIDGET, scrolling is
8757  * irrelevant, the child floats above all scrollable areas. But when
8758  * placing a child in one of the scrollable windows (border windows or
8759  * text window), you'll need to compute the child's correct position
8760  * in buffer coordinates any time scrolling occurs or buffer changes
8761  * occur, and then call gtk_text_view_move_child() to update the
8762  * child's position. Unfortunately there's no good way to detect that
8763  * scrolling has occurred, using the current API; a possible hack
8764  * would be to update all child positions when the scroll adjustments
8765  * change or the text buffer changes. See bug 64518 on
8766  * bugzilla.gnome.org for status of fixing this issue.
8767  **/
8768 void
8769 gtk_text_view_add_child_in_window (GtkTextView       *text_view,
8770                                    GtkWidget         *child,
8771                                    GtkTextWindowType  which_window,
8772                                    gint               xpos,
8773                                    gint               ypos)
8774 {
8775   GtkTextViewChild *vc;
8776
8777   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
8778   g_return_if_fail (GTK_IS_WIDGET (child));
8779   g_return_if_fail (child->parent == NULL);
8780
8781   vc = text_view_child_new_window (child, which_window,
8782                                    xpos, ypos);
8783
8784   add_child (text_view, vc);
8785
8786   g_assert (vc->widget == child);
8787   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
8788 }
8789
8790 /**
8791  * gtk_text_view_move_child:
8792  * @text_view: a #GtkTextView
8793  * @child: child widget already added to the text view
8794  * @xpos: new X position in window coordinates
8795  * @ypos: new Y position in window coordinates
8796  *
8797  * Updates the position of a child, as for gtk_text_view_add_child_in_window().
8798  **/
8799 void
8800 gtk_text_view_move_child (GtkTextView *text_view,
8801                           GtkWidget   *child,
8802                           gint         xpos,
8803                           gint         ypos)
8804 {
8805   GtkTextViewChild *vc;
8806
8807   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
8808   g_return_if_fail (GTK_IS_WIDGET (child));
8809   g_return_if_fail (child->parent == (GtkWidget*) text_view);
8810
8811   vc = g_object_get_data (G_OBJECT (child),
8812                           "gtk-text-view-child");
8813
8814   g_assert (vc != NULL);
8815
8816   if (vc->x == xpos &&
8817       vc->y == ypos)
8818     return;
8819   
8820   vc->x = xpos;
8821   vc->y = ypos;
8822
8823   if (GTK_WIDGET_VISIBLE (child) && GTK_WIDGET_VISIBLE (text_view))
8824     gtk_widget_queue_resize (child);
8825 }
8826
8827
8828 /* Iterator operations */
8829
8830 /**
8831  * gtk_text_view_forward_display_line:
8832  * @text_view: a #GtkTextView
8833  * @iter: a #GtkTextIter
8834  * 
8835  * Moves the given @iter forward by one display (wrapped) line.
8836  * A display line is different from a paragraph. Paragraphs are
8837  * separated by newlines or other paragraph separator characters.
8838  * Display lines are created by line-wrapping a paragraph. If
8839  * wrapping is turned off, display lines and paragraphs will be the
8840  * same. Display lines are divided differently for each view, since
8841  * they depend on the view's width; paragraphs are the same in all
8842  * views, since they depend on the contents of the #GtkTextBuffer.
8843  * 
8844  * Return value: %TRUE if @iter was moved and is not on the end iterator
8845  **/
8846 gboolean
8847 gtk_text_view_forward_display_line (GtkTextView *text_view,
8848                                     GtkTextIter *iter)
8849 {
8850   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
8851   g_return_val_if_fail (iter != NULL, FALSE);
8852
8853   gtk_text_view_ensure_layout (text_view);
8854
8855   return gtk_text_layout_move_iter_to_next_line (text_view->layout, iter);
8856 }
8857
8858 /**
8859  * gtk_text_view_backward_display_line:
8860  * @text_view: a #GtkTextView
8861  * @iter: a #GtkTextIter
8862  * 
8863  * Moves the given @iter backward by one display (wrapped) line.
8864  * A display line is different from a paragraph. Paragraphs are
8865  * separated by newlines or other paragraph separator characters.
8866  * Display lines are created by line-wrapping a paragraph. If
8867  * wrapping is turned off, display lines and paragraphs will be the
8868  * same. Display lines are divided differently for each view, since
8869  * they depend on the view's width; paragraphs are the same in all
8870  * views, since they depend on the contents of the #GtkTextBuffer.
8871  * 
8872  * Return value: %TRUE if @iter was moved and is not on the end iterator
8873  **/
8874 gboolean
8875 gtk_text_view_backward_display_line (GtkTextView *text_view,
8876                                      GtkTextIter *iter)
8877 {
8878   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
8879   g_return_val_if_fail (iter != NULL, FALSE);
8880
8881   gtk_text_view_ensure_layout (text_view);
8882
8883   return gtk_text_layout_move_iter_to_previous_line (text_view->layout, iter);
8884 }
8885
8886 /**
8887  * gtk_text_view_forward_display_line_end:
8888  * @text_view: a #GtkTextView
8889  * @iter: a #GtkTextIter
8890  * 
8891  * Moves the given @iter forward to the next display line end.
8892  * A display line is different from a paragraph. Paragraphs are
8893  * separated by newlines or other paragraph separator characters.
8894  * Display lines are created by line-wrapping a paragraph. If
8895  * wrapping is turned off, display lines and paragraphs will be the
8896  * same. Display lines are divided differently for each view, since
8897  * they depend on the view's width; paragraphs are the same in all
8898  * views, since they depend on the contents of the #GtkTextBuffer.
8899  * 
8900  * Return value: %TRUE if @iter was moved and is not on the end iterator
8901  **/
8902 gboolean
8903 gtk_text_view_forward_display_line_end (GtkTextView *text_view,
8904                                         GtkTextIter *iter)
8905 {
8906   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
8907   g_return_val_if_fail (iter != NULL, FALSE);
8908
8909   gtk_text_view_ensure_layout (text_view);
8910
8911   return gtk_text_layout_move_iter_to_line_end (text_view->layout, iter, 1);
8912 }
8913
8914 /**
8915  * gtk_text_view_backward_display_line_start:
8916  * @text_view: a #GtkTextView
8917  * @iter: a #GtkTextIter
8918  * 
8919  * Moves the given @iter backward to the next display line start.
8920  * A display line is different from a paragraph. Paragraphs are
8921  * separated by newlines or other paragraph separator characters.
8922  * Display lines are created by line-wrapping a paragraph. If
8923  * wrapping is turned off, display lines and paragraphs will be the
8924  * same. Display lines are divided differently for each view, since
8925  * they depend on the view's width; paragraphs are the same in all
8926  * views, since they depend on the contents of the #GtkTextBuffer.
8927  * 
8928  * Return value: %TRUE if @iter was moved and is not on the end iterator
8929  **/
8930 gboolean
8931 gtk_text_view_backward_display_line_start (GtkTextView *text_view,
8932                                            GtkTextIter *iter)
8933 {
8934   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
8935   g_return_val_if_fail (iter != NULL, FALSE);
8936
8937   gtk_text_view_ensure_layout (text_view);
8938
8939   return gtk_text_layout_move_iter_to_line_end (text_view->layout, iter, -1);
8940 }
8941
8942 /**
8943  * gtk_text_view_starts_display_line:
8944  * @text_view: a #GtkTextView
8945  * @iter: a #GtkTextIter
8946  * 
8947  * Determines whether @iter is at the start of a display line.
8948  * See gtk_text_view_forward_display_line() for an explanation of
8949  * display lines vs. paragraphs.
8950  * 
8951  * Return value: %TRUE if @iter begins a wrapped line
8952  **/
8953 gboolean
8954 gtk_text_view_starts_display_line (GtkTextView       *text_view,
8955                                    const GtkTextIter *iter)
8956 {
8957   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
8958   g_return_val_if_fail (iter != NULL, FALSE);
8959
8960   gtk_text_view_ensure_layout (text_view);
8961
8962   return gtk_text_layout_iter_starts_line (text_view->layout, iter);
8963 }
8964
8965 /**
8966  * gtk_text_view_move_visually:
8967  * @text_view: a #GtkTextView
8968  * @iter: a #GtkTextIter
8969  * @count: number of characters to move (negative moves left, 
8970  *    positive moves right)
8971  *
8972  * Move the iterator a given number of characters visually, treating
8973  * it as the strong cursor position. If @count is positive, then the
8974  * new strong cursor position will be @count positions to the right of
8975  * the old cursor position. If @count is negative then the new strong
8976  * cursor position will be @count positions to the left of the old
8977  * cursor position.
8978  *
8979  * In the presence of bi-directional text, the correspondence
8980  * between logical and visual order will depend on the direction
8981  * of the current run, and there may be jumps when the cursor
8982  * is moved off of the end of a run.
8983  * 
8984  * Return value: %TRUE if @iter moved and is not on the end iterator
8985  **/
8986 gboolean
8987 gtk_text_view_move_visually (GtkTextView *text_view,
8988                              GtkTextIter *iter,
8989                              gint         count)
8990 {
8991   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
8992   g_return_val_if_fail (iter != NULL, FALSE);
8993
8994   gtk_text_view_ensure_layout (text_view);
8995
8996   return gtk_text_layout_move_iter_visually (text_view->layout, iter, count);
8997 }
8998
8999 #define __GTK_TEXT_VIEW_C__
9000 #include "gtkaliasdef.c"