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