]> Pileus Git - ~andy/gtk/blob - gtk/gtktext.c
Add hidden aliases for exported symbols which are used internally in order
[~andy/gtk] / gtk / gtktext.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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 #undef GDK_DISABLE_DEPRECATED
28 #undef GTK_DISABLE_DEPRECATED
29
30 #include <config.h>
31 #include <ctype.h>
32 #include <string.h>
33 #include "gdk/gdkkeysyms.h"
34 #include "gdk/gdki18n.h"
35 #include "gtkalias.h"
36 #include "gtkmain.h"
37 #include "gtkmarshalers.h"
38 #include "gtkselection.h"
39 #include "gtksignal.h"
40 #define GTK_ENABLE_BROKEN
41 #include "gtktext.h"
42 #include "line-wrap.xbm"
43 #include "line-arrow.xbm"
44 #include "gtkintl.h"
45
46
47 #define INITIAL_BUFFER_SIZE      1024
48 #define INITIAL_LINE_CACHE_SIZE  256
49 #define MIN_GAP_SIZE             256
50 #define LINE_DELIM               '\n'
51 #define MIN_TEXT_WIDTH_LINES     20
52 #define MIN_TEXT_HEIGHT_LINES    10
53 #define TEXT_BORDER_ROOM         1
54 #define LINE_WRAP_ROOM           8           /* The bitmaps are 6 wide. */
55 #define DEFAULT_TAB_STOP_WIDTH   4
56 #define SCROLL_PIXELS            5
57 #define KEY_SCROLL_PIXELS        10
58 #define SCROLL_TIME              100
59 #define FREEZE_LENGTH            1024        
60 /* Freeze text when inserting or deleting more than this many characters */
61
62 #define SET_PROPERTY_MARK(m, p, o)  do {                   \
63                                       (m)->property = (p); \
64                                       (m)->offset = (o);   \
65                                     } while (0)
66 #define MARK_CURRENT_PROPERTY(mark) ((TextProperty*)(mark)->property->data)
67 #define MARK_NEXT_PROPERTY(mark)    ((TextProperty*)(mark)->property->next->data)
68 #define MARK_PREV_PROPERTY(mark)    ((TextProperty*)((mark)->property->prev ?     \
69                                                      (mark)->property->prev->data \
70                                                      : NULL))
71 #define MARK_PREV_LIST_PTR(mark)    ((mark)->property->prev)
72 #define MARK_LIST_PTR(mark)         ((mark)->property)
73 #define MARK_NEXT_LIST_PTR(mark)    ((mark)->property->next)
74 #define MARK_OFFSET(mark)           ((mark)->offset)
75 #define MARK_PROPERTY_LENGTH(mark)  (MARK_CURRENT_PROPERTY(mark)->length)
76
77
78 #define MARK_CURRENT_FONT(text, mark) \
79   ((MARK_CURRENT_PROPERTY(mark)->flags & PROPERTY_FONT) ? \
80          MARK_CURRENT_PROPERTY(mark)->font->gdk_font : \
81          gtk_style_get_font (GTK_WIDGET (text)->style))
82 #define MARK_CURRENT_FORE(text, mark) \
83   ((MARK_CURRENT_PROPERTY(mark)->flags & PROPERTY_FOREGROUND) ? \
84          &MARK_CURRENT_PROPERTY(mark)->fore_color : \
85          &((GtkWidget *)text)->style->text[((GtkWidget *)text)->state])
86 #define MARK_CURRENT_BACK(text, mark) \
87   ((MARK_CURRENT_PROPERTY(mark)->flags & PROPERTY_BACKGROUND) ? \
88          &MARK_CURRENT_PROPERTY(mark)->back_color : \
89          &((GtkWidget *)text)->style->base[((GtkWidget *)text)->state])
90 #define MARK_CURRENT_TEXT_FONT(text, mark) \
91   ((MARK_CURRENT_PROPERTY(mark)->flags & PROPERTY_FONT) ? \
92          MARK_CURRENT_PROPERTY(mark)->font : \
93          text->current_font)
94
95 #define TEXT_LENGTH(t)              ((t)->text_end - (t)->gap_size)
96 #define FONT_HEIGHT(f)              ((f)->ascent + (f)->descent)
97 #define LINE_HEIGHT(l)              ((l).font_ascent + (l).font_descent)
98 #define LINE_CONTAINS(l, i)         ((l).start.index <= (i) && (l).end.index >= (i))
99 #define LINE_STARTS_AT(l, i)        ((l).start.index == (i))
100 #define LINE_START_PIXEL(l)         ((l).tab_cont.pixel_offset)
101 #define LAST_INDEX(t, m)            ((m).index == TEXT_LENGTH(t))
102 #define CACHE_DATA(c)               (*(LineParams*)(c)->data)
103
104 enum {
105   PROP_0,
106   PROP_HADJUSTMENT,
107   PROP_VADJUSTMENT,
108   PROP_LINE_WRAP,
109   PROP_WORD_WRAP
110 };
111
112 typedef struct _TextProperty          TextProperty;
113 typedef struct _TabStopMark           TabStopMark;
114 typedef struct _PrevTabCont           PrevTabCont;
115 typedef struct _FetchLinesData        FetchLinesData;
116 typedef struct _LineParams            LineParams;
117 typedef struct _SetVerticalScrollData SetVerticalScrollData;
118
119 typedef gint (*LineIteratorFunction) (GtkText* text, LineParams* lp, void* data);
120
121 typedef enum
122 {
123   FetchLinesPixels,
124   FetchLinesCount
125 } FLType;
126
127 struct _SetVerticalScrollData {
128   gint pixel_height;
129   gint last_didnt_wrap;
130   gint last_line_start;
131   GtkPropertyMark mark;
132 };
133
134 struct _GtkTextFont
135 {
136   /* The actual font. */
137   GdkFont *gdk_font;
138   guint ref_count;
139
140   gint16 char_widths[256];
141 };
142
143 typedef enum {
144   PROPERTY_FONT =       1 << 0,
145   PROPERTY_FOREGROUND = 1 << 1,
146   PROPERTY_BACKGROUND = 1 << 2
147 } TextPropertyFlags;
148
149 struct _TextProperty
150 {
151   /* Font. */
152   GtkTextFont* font;
153
154   /* Background Color. */
155   GdkColor back_color;
156   
157   /* Foreground Color. */
158   GdkColor fore_color;
159
160   /* Show which properties are set */
161   TextPropertyFlags flags;
162
163   /* Length of this property. */
164   guint length;
165 };
166
167 struct _TabStopMark
168 {
169   GList* tab_stops; /* Index into list containing the next tab position.  If
170                      * NULL, using default widths. */
171   gint to_next_tab;
172 };
173
174 struct _PrevTabCont
175 {
176   guint pixel_offset;
177   TabStopMark tab_start;
178 };
179
180 struct _FetchLinesData
181 {
182   GList* new_lines;
183   FLType fl_type;
184   gint data;
185   gint data_max;
186 };
187
188 struct _LineParams
189 {
190   guint font_ascent;
191   guint font_descent;
192   guint pixel_width;
193   guint displayable_chars;
194   guint wraps : 1;
195   
196   PrevTabCont tab_cont;
197   PrevTabCont tab_cont_next;
198   
199   GtkPropertyMark start;
200   GtkPropertyMark end;
201 };
202
203
204 static void  gtk_text_class_init     (GtkTextClass   *klass);
205 static void  gtk_text_set_property   (GObject         *object,
206                                       guint            prop_id,
207                                       const GValue    *value,
208                                       GParamSpec      *pspec);
209 static void  gtk_text_get_property   (GObject         *object,
210                                       guint            prop_id,
211                                       GValue          *value,
212                                       GParamSpec      *pspec);
213 static void  gtk_text_editable_init  (GtkEditableClass *iface);
214 static void  gtk_text_init           (GtkText        *text);
215 static void  gtk_text_destroy        (GtkObject      *object);
216 static void  gtk_text_finalize       (GObject        *object);
217 static void  gtk_text_realize        (GtkWidget      *widget);
218 static void  gtk_text_unrealize      (GtkWidget      *widget);
219 static void  gtk_text_style_set      (GtkWidget      *widget,
220                                       GtkStyle       *previous_style);
221 static void  gtk_text_state_changed  (GtkWidget      *widget,
222                                       GtkStateType    previous_state);
223 static void  gtk_text_draw_focus     (GtkWidget      *widget);
224 static void  gtk_text_size_request   (GtkWidget      *widget,
225                                       GtkRequisition *requisition);
226 static void  gtk_text_size_allocate  (GtkWidget      *widget,
227                                       GtkAllocation  *allocation);
228 static void  gtk_text_adjustment     (GtkAdjustment  *adjustment,
229                                       GtkText        *text);
230 static void   gtk_text_insert_text       (GtkEditable    *editable,
231                                           const gchar    *new_text,
232                                           gint            new_text_length,
233                                           gint           *position);
234 static void   gtk_text_delete_text       (GtkEditable    *editable,
235                                           gint            start_pos,
236                                           gint            end_pos);
237 static void   gtk_text_update_text       (GtkOldEditable *old_editable,
238                                           gint            start_pos,
239                                           gint            end_pos);
240 static gchar *gtk_text_get_chars         (GtkOldEditable *old_editable,
241                                           gint            start,
242                                           gint            end);
243 static void   gtk_text_set_selection     (GtkOldEditable *old_editable,
244                                           gint            start,
245                                           gint            end);
246 static void   gtk_text_real_set_editable (GtkOldEditable *old_editable,
247                                           gboolean        is_editable);
248
249 static void  gtk_text_adjustment_destroyed (GtkAdjustment  *adjustment,
250                                             GtkText        *text);
251
252 /* Event handlers */
253 static gint  gtk_text_expose            (GtkWidget         *widget,
254                                          GdkEventExpose    *event);
255 static gint  gtk_text_button_press      (GtkWidget         *widget,
256                                          GdkEventButton    *event);
257 static gint  gtk_text_button_release    (GtkWidget         *widget,
258                                          GdkEventButton    *event);
259 static gint  gtk_text_motion_notify     (GtkWidget         *widget,
260                                          GdkEventMotion    *event);
261 static gint  gtk_text_key_press         (GtkWidget         *widget,
262                                          GdkEventKey       *event);
263
264 static void move_gap (GtkText* text, guint index);
265 static void make_forward_space (GtkText* text, guint len);
266
267 /* Property management */
268 static GtkTextFont* get_text_font (GdkFont* gfont);
269 static void         text_font_unref (GtkTextFont *text_font);
270
271 static void insert_text_property (GtkText* text, GdkFont* font,
272                                   const GdkColor *fore, const GdkColor* back, guint len);
273 static TextProperty* new_text_property (GtkText *text, GdkFont* font, 
274                                         const GdkColor* fore, const GdkColor* back, guint length);
275 static void destroy_text_property (TextProperty *prop);
276 static void init_properties      (GtkText *text);
277 static void realize_property     (GtkText *text, TextProperty *prop);
278 static void realize_properties   (GtkText *text);
279 static void unrealize_property   (GtkText *text, TextProperty *prop);
280 static void unrealize_properties (GtkText *text);
281
282 static void delete_text_property (GtkText* text, guint len);
283
284 static guint pixel_height_of (GtkText* text, GList* cache_line);
285
286 /* Property Movement and Size Computations */
287 static void advance_mark (GtkPropertyMark* mark);
288 static void decrement_mark (GtkPropertyMark* mark);
289 static void advance_mark_n (GtkPropertyMark* mark, gint n);
290 static void decrement_mark_n (GtkPropertyMark* mark, gint n);
291 static void move_mark_n (GtkPropertyMark* mark, gint n);
292 static GtkPropertyMark find_mark (GtkText* text, guint mark_position);
293 static GtkPropertyMark find_mark_near (GtkText* text, guint mark_position, const GtkPropertyMark* near);
294 static void find_line_containing_point (GtkText* text, guint point,
295                                         gboolean scroll);
296
297 /* Display */
298 static void compute_lines_pixels (GtkText* text, guint char_count,
299                                   guint *lines, guint *pixels);
300
301 static gint total_line_height (GtkText* text,
302                                GList* line,
303                                gint line_count);
304 static LineParams find_line_params (GtkText* text,
305                                     const GtkPropertyMark *mark,
306                                     const PrevTabCont *tab_cont,
307                                     PrevTabCont *next_cont);
308 static void recompute_geometry (GtkText* text);
309 static void insert_expose (GtkText* text, guint old_pixels, gint nchars, guint new_line_count);
310 static void delete_expose (GtkText* text,
311                            guint nchars,
312                            guint old_lines, 
313                            guint old_pixels);
314 static GdkGC *create_bg_gc (GtkText *text);
315 static void clear_area (GtkText *text, GdkRectangle *area);
316 static void draw_line (GtkText* text,
317                        gint pixel_height,
318                        LineParams* lp);
319 static void draw_line_wrap (GtkText* text,
320                             guint height);
321 static void draw_cursor (GtkText* text, gint absolute);
322 static void undraw_cursor (GtkText* text, gint absolute);
323 static gint drawn_cursor_min (GtkText* text);
324 static gint drawn_cursor_max (GtkText* text);
325 static void expose_text (GtkText* text, GdkRectangle *area, gboolean cursor);
326
327 /* Search and Placement. */
328 static void find_cursor (GtkText* text,
329                          gboolean scroll);
330 static void find_cursor_at_line (GtkText* text,
331                                  const LineParams* start_line,
332                                  gint pixel_height);
333 static void find_mouse_cursor (GtkText* text, gint x, gint y);
334
335 /* Scrolling. */
336 static void adjust_adj  (GtkText* text, GtkAdjustment* adj);
337 static void scroll_up   (GtkText* text, gint diff);
338 static void scroll_down (GtkText* text, gint diff);
339 static void scroll_int  (GtkText* text, gint diff);
340
341 static void process_exposes (GtkText *text);
342
343 /* Cache Management. */
344 static void   free_cache        (GtkText* text);
345 static GList* remove_cache_line (GtkText* text, GList* list);
346
347 /* Key Motion. */
348 static void move_cursor_buffer_ver (GtkText *text, int dir);
349 static void move_cursor_page_ver (GtkText *text, int dir);
350 static void move_cursor_ver (GtkText *text, int count);
351 static void move_cursor_hor (GtkText *text, int count);
352
353 /* Binding actions */
354 static void gtk_text_move_cursor    (GtkOldEditable *old_editable,
355                                      gint            x,
356                                      gint            y);
357 static void gtk_text_move_word      (GtkOldEditable *old_editable,
358                                      gint            n);
359 static void gtk_text_move_page      (GtkOldEditable *old_editable,
360                                      gint            x,
361                                      gint            y);
362 static void gtk_text_move_to_row    (GtkOldEditable *old_editable,
363                                      gint            row);
364 static void gtk_text_move_to_column (GtkOldEditable *old_editable,
365                                      gint            row);
366 static void gtk_text_kill_char      (GtkOldEditable *old_editable,
367                                      gint            direction);
368 static void gtk_text_kill_word      (GtkOldEditable *old_editable,
369                                      gint            direction);
370 static void gtk_text_kill_line      (GtkOldEditable *old_editable,
371                                      gint            direction);
372
373 /* To be removed */
374 static void gtk_text_move_forward_character    (GtkText          *text);
375 static void gtk_text_move_backward_character   (GtkText          *text);
376 static void gtk_text_move_forward_word         (GtkText          *text);
377 static void gtk_text_move_backward_word        (GtkText          *text);
378 static void gtk_text_move_beginning_of_line    (GtkText          *text);
379 static void gtk_text_move_end_of_line          (GtkText          *text);
380 static void gtk_text_move_next_line            (GtkText          *text);
381 static void gtk_text_move_previous_line        (GtkText          *text);
382
383 static void gtk_text_delete_forward_character  (GtkText          *text);
384 static void gtk_text_delete_backward_character (GtkText          *text);
385 static void gtk_text_delete_forward_word       (GtkText          *text);
386 static void gtk_text_delete_backward_word      (GtkText          *text);
387 static void gtk_text_delete_line               (GtkText          *text);
388 static void gtk_text_delete_to_line_end        (GtkText          *text);
389 static void gtk_text_select_word               (GtkText          *text,
390                                                 guint32           time);
391 static void gtk_text_select_line               (GtkText          *text,
392                                                 guint32           time);
393
394 static void gtk_text_set_position (GtkOldEditable *old_editable,
395                                    gint            position);
396
397 /* #define DEBUG_GTK_TEXT */
398
399 #if defined(DEBUG_GTK_TEXT) && defined(__GNUC__)
400 /* Debugging utilities. */
401 static void gtk_text_assert_mark (GtkText         *text,
402                                   GtkPropertyMark *mark,
403                                   GtkPropertyMark *before,
404                                   GtkPropertyMark *after,
405                                   const gchar     *msg,
406                                   const gchar     *where,
407                                   gint             line);
408
409 static void gtk_text_assert (GtkText         *text,
410                              const gchar     *msg,
411                              gint             line);
412 static void gtk_text_show_cache_line (GtkText *text, GList *cache,
413                                       const char* what, const char* func, gint line);
414 static void gtk_text_show_cache (GtkText *text, const char* func, gint line);
415 static void gtk_text_show_adj (GtkText *text,
416                                GtkAdjustment *adj,
417                                const char* what,
418                                const char* func,
419                                gint line);
420 static void gtk_text_show_props (GtkText* test,
421                                  const char* func,
422                                  int line);
423
424 #define TDEBUG(args) g_message args
425 #define TEXT_ASSERT(text) gtk_text_assert (text,__PRETTY_FUNCTION__,__LINE__)
426 #define TEXT_ASSERT_MARK(text,mark,msg) gtk_text_assert_mark (text,mark, \
427                                            __PRETTY_FUNCTION__,msg,__LINE__)
428 #define TEXT_SHOW(text) gtk_text_show_cache (text, __PRETTY_FUNCTION__,__LINE__)
429 #define TEXT_SHOW_LINE(text,line,msg) gtk_text_show_cache_line (text,line,msg,\
430                                            __PRETTY_FUNCTION__,__LINE__)
431 #define TEXT_SHOW_ADJ(text,adj,msg) gtk_text_show_adj (text,adj,msg, \
432                                           __PRETTY_FUNCTION__,__LINE__)
433 #else
434 #define TDEBUG(args)
435 #define TEXT_ASSERT(text)
436 #define TEXT_ASSERT_MARK(text,mark,msg)
437 #define TEXT_SHOW(text)
438 #define TEXT_SHOW_LINE(text,line,msg)
439 #define TEXT_SHOW_ADJ(text,adj,msg)
440 #endif
441
442 /* Memory Management. */
443 static GMemChunk  *params_mem_chunk    = NULL;
444 static GMemChunk  *text_property_chunk = NULL;
445
446 static GtkWidgetClass *parent_class = NULL;
447
448
449 static const GtkTextFunction control_keys[26] =
450 {
451   (GtkTextFunction)gtk_text_move_beginning_of_line,    /* a */
452   (GtkTextFunction)gtk_text_move_backward_character,   /* b */
453   (GtkTextFunction)gtk_editable_copy_clipboard,        /* c */
454   (GtkTextFunction)gtk_text_delete_forward_character,  /* d */
455   (GtkTextFunction)gtk_text_move_end_of_line,          /* e */
456   (GtkTextFunction)gtk_text_move_forward_character,    /* f */
457   NULL,                                                /* g */
458   (GtkTextFunction)gtk_text_delete_backward_character, /* h */
459   NULL,                                                /* i */
460   NULL,                                                /* j */
461   (GtkTextFunction)gtk_text_delete_to_line_end,        /* k */
462   NULL,                                                /* l */
463   NULL,                                                /* m */
464   (GtkTextFunction)gtk_text_move_next_line,            /* n */
465   NULL,                                                /* o */
466   (GtkTextFunction)gtk_text_move_previous_line,        /* p */
467   NULL,                                                /* q */
468   NULL,                                                /* r */
469   NULL,                                                /* s */
470   NULL,                                                /* t */
471   (GtkTextFunction)gtk_text_delete_line,               /* u */
472   (GtkTextFunction)gtk_editable_paste_clipboard,       /* v */
473   (GtkTextFunction)gtk_text_delete_backward_word,      /* w */
474   (GtkTextFunction)gtk_editable_cut_clipboard,         /* x */
475   NULL,                                                /* y */
476   NULL,                                                /* z */
477 };
478
479 static const GtkTextFunction alt_keys[26] =
480 {
481   NULL,                                                /* a */
482   (GtkTextFunction)gtk_text_move_backward_word,        /* b */
483   NULL,                                                /* c */
484   (GtkTextFunction)gtk_text_delete_forward_word,       /* d */
485   NULL,                                           /* e */
486   (GtkTextFunction)gtk_text_move_forward_word,         /* f */
487   NULL,                                           /* g */
488   NULL,                                           /* h */
489   NULL,                                           /* i */
490   NULL,                                           /* j */
491   NULL,                                           /* k */
492   NULL,                                           /* l */
493   NULL,                                           /* m */
494   NULL,                                           /* n */
495   NULL,                                           /* o */
496   NULL,                                           /* p */
497   NULL,                                           /* q */
498   NULL,                                           /* r */
499   NULL,                                           /* s */
500   NULL,                                           /* t */
501   NULL,                                           /* u */
502   NULL,                                           /* v */
503   NULL,                                           /* w */
504   NULL,                                           /* x */
505   NULL,                                           /* y */
506   NULL,                                           /* z */
507 };
508
509
510 /**********************************************************************/
511 /*                              Widget Crap                           */
512 /**********************************************************************/
513
514 GtkType
515 gtk_text_get_type (void)
516 {
517   static GtkType text_type = 0;
518   
519   if (!text_type)
520     {
521       static const GtkTypeInfo text_info =
522       {
523         "GtkText",
524         sizeof (GtkText),
525         sizeof (GtkTextClass),
526         (GtkClassInitFunc) gtk_text_class_init,
527         (GtkObjectInitFunc) gtk_text_init,
528         /* reserved_1 */ NULL,
529         /* reserved_2 */ NULL,
530         (GtkClassInitFunc) NULL,
531       };
532
533       static const GInterfaceInfo editable_info =
534       {
535         (GInterfaceInitFunc) gtk_text_editable_init, /* interface_init */
536         NULL, /* interface_finalize */
537         NULL  /* interface_data */
538       };
539       
540       text_type = gtk_type_unique (GTK_TYPE_OLD_EDITABLE, &text_info);
541       g_type_add_interface_static (text_type,
542                                    GTK_TYPE_EDITABLE,
543                                    &editable_info);
544     }
545   
546   return text_type;
547 }
548
549 static void
550 gtk_text_class_init (GtkTextClass *class)
551 {
552   GObjectClass *gobject_class;
553   GtkObjectClass *object_class;
554   GtkWidgetClass *widget_class;
555   GtkOldEditableClass *old_editable_class;
556
557   gobject_class = G_OBJECT_CLASS (class);
558   object_class = (GtkObjectClass*) class;
559   widget_class = (GtkWidgetClass*) class;
560   old_editable_class = (GtkOldEditableClass*) class;
561   parent_class = gtk_type_class (GTK_TYPE_OLD_EDITABLE);
562
563   gobject_class->finalize = gtk_text_finalize;
564   gobject_class->set_property = gtk_text_set_property;
565   gobject_class->get_property = gtk_text_get_property;
566   
567   object_class->destroy = gtk_text_destroy;
568   
569   widget_class->realize = gtk_text_realize;
570   widget_class->unrealize = gtk_text_unrealize;
571   widget_class->style_set = gtk_text_style_set;
572   widget_class->state_changed = gtk_text_state_changed;
573   widget_class->size_request = gtk_text_size_request;
574   widget_class->size_allocate = gtk_text_size_allocate;
575   widget_class->expose_event = gtk_text_expose;
576   widget_class->button_press_event = gtk_text_button_press;
577   widget_class->button_release_event = gtk_text_button_release;
578   widget_class->motion_notify_event = gtk_text_motion_notify;
579   widget_class->key_press_event = gtk_text_key_press;
580
581   old_editable_class->set_editable = gtk_text_real_set_editable;
582   
583   old_editable_class->move_cursor = gtk_text_move_cursor;
584   old_editable_class->move_word = gtk_text_move_word;
585   old_editable_class->move_page = gtk_text_move_page;
586   old_editable_class->move_to_row = gtk_text_move_to_row;
587   old_editable_class->move_to_column = gtk_text_move_to_column;
588   
589   old_editable_class->kill_char = gtk_text_kill_char;
590   old_editable_class->kill_word = gtk_text_kill_word;
591   old_editable_class->kill_line = gtk_text_kill_line;
592   
593   old_editable_class->update_text = gtk_text_update_text;
594   old_editable_class->get_chars   = gtk_text_get_chars;
595   old_editable_class->set_selection = gtk_text_set_selection;
596   old_editable_class->set_position = gtk_text_set_position;
597
598   class->set_scroll_adjustments = gtk_text_set_adjustments;
599
600   g_object_class_install_property (gobject_class,
601                                    PROP_HADJUSTMENT,
602                                    g_param_spec_object ("hadjustment",
603                                                         P_("Horizontal Adjustment"),
604                                                         P_("Horizontal adjustment for the text widget"),
605                                                         GTK_TYPE_ADJUSTMENT,
606                                                         G_PARAM_READWRITE));
607
608   g_object_class_install_property (gobject_class,
609                                    PROP_VADJUSTMENT,
610                                    g_param_spec_object ("vadjustment",
611                                                         P_("Vertical Adjustment"),
612                                                         P_("Vertical adjustment for the text widget"),
613                                                         GTK_TYPE_ADJUSTMENT,
614                                                         G_PARAM_READWRITE));
615
616   g_object_class_install_property (gobject_class,
617                                    PROP_LINE_WRAP,
618                                    g_param_spec_boolean ("line_wrap",
619                                                          P_("Line Wrap"),
620                                                          P_("Whether lines are wrapped at widget edges"),
621                                                          TRUE,
622                                                          G_PARAM_READWRITE));
623
624   g_object_class_install_property (gobject_class,
625                                    PROP_WORD_WRAP,
626                                    g_param_spec_boolean ("word_wrap",
627                                                          P_("Word Wrap"),
628                                                          P_("Whether words are wrapped at widget edges"),
629                                                          FALSE,
630                                                          G_PARAM_READWRITE));
631
632   widget_class->set_scroll_adjustments_signal =
633     gtk_signal_new ("set_scroll_adjustments",
634                     GTK_RUN_LAST,
635                     GTK_CLASS_TYPE (object_class),
636                     GTK_SIGNAL_OFFSET (GtkTextClass, set_scroll_adjustments),
637                     _gtk_marshal_VOID__OBJECT_OBJECT,
638                     GTK_TYPE_NONE, 2, GTK_TYPE_ADJUSTMENT, GTK_TYPE_ADJUSTMENT);
639 }
640
641 static void
642 gtk_text_set_property (GObject         *object,
643                        guint            prop_id,
644                        const GValue    *value,
645                        GParamSpec      *pspec)
646 {
647   GtkText *text;
648   
649   text = GTK_TEXT (object);
650   
651   switch (prop_id)
652     {
653     case PROP_HADJUSTMENT:
654       gtk_text_set_adjustments (text,
655                                 g_value_get_object (value),
656                                 text->vadj);
657       break;
658     case PROP_VADJUSTMENT:
659       gtk_text_set_adjustments (text,
660                                 text->hadj,
661                                 g_value_get_object (value));
662       break;
663     case PROP_LINE_WRAP:
664       gtk_text_set_line_wrap (text, g_value_get_boolean (value));
665       break;
666     case PROP_WORD_WRAP:
667       gtk_text_set_word_wrap (text, g_value_get_boolean (value));
668       break;
669     default:
670       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
671       break;
672     }
673 }
674
675 static void
676 gtk_text_get_property (GObject         *object,
677                        guint            prop_id,
678                        GValue          *value,
679                        GParamSpec      *pspec)
680 {
681   GtkText *text;
682   
683   text = GTK_TEXT (object);
684   
685   switch (prop_id)
686     {
687     case PROP_HADJUSTMENT:
688       g_value_set_object (value, text->hadj);
689       break;
690     case PROP_VADJUSTMENT:
691       g_value_set_object (value, text->vadj);
692       break;
693     case PROP_LINE_WRAP:
694       g_value_set_boolean (value, text->line_wrap);
695       break;
696     case PROP_WORD_WRAP:
697       g_value_set_boolean (value, text->word_wrap);
698       break;
699     default:
700       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
701       break;
702     }
703 }
704
705 static void
706 gtk_text_editable_init (GtkEditableClass *iface)
707 {
708   iface->insert_text = gtk_text_insert_text;
709   iface->delete_text = gtk_text_delete_text;
710 }
711
712 static void
713 gtk_text_init (GtkText *text)
714 {
715   GTK_WIDGET_SET_FLAGS (text, GTK_CAN_FOCUS);
716
717   text->text_area = NULL;
718   text->hadj = NULL;
719   text->vadj = NULL;
720   text->gc = NULL;
721   text->bg_gc = NULL;
722   text->line_wrap_bitmap = NULL;
723   text->line_arrow_bitmap = NULL;
724   
725   text->use_wchar = FALSE;
726   text->text.ch = g_new (guchar, INITIAL_BUFFER_SIZE);
727   text->text_len = INITIAL_BUFFER_SIZE;
728  
729   text->scratch_buffer.ch = NULL;
730   text->scratch_buffer_len = 0;
731  
732   text->freeze_count = 0;
733   
734   if (!params_mem_chunk)
735     params_mem_chunk = g_mem_chunk_new ("LineParams",
736                                         sizeof (LineParams),
737                                         256 * sizeof (LineParams),
738                                         G_ALLOC_AND_FREE);
739   
740   text->default_tab_width = 4;
741   text->tab_stops = NULL;
742   
743   text->tab_stops = g_list_prepend (text->tab_stops, (void*)8);
744   text->tab_stops = g_list_prepend (text->tab_stops, (void*)8);
745   
746   text->line_start_cache = NULL;
747   text->first_cut_pixels = 0;
748   
749   text->line_wrap = TRUE;
750   text->word_wrap = FALSE;
751   
752   text->timer = 0;
753   text->button = 0;
754   
755   text->current_font = NULL;
756   
757   init_properties (text);
758   
759   GTK_OLD_EDITABLE (text)->editable = FALSE;
760   
761   gtk_text_set_adjustments (text, NULL, NULL);
762   gtk_editable_set_position (GTK_EDITABLE (text), 0);
763 }
764
765 GtkWidget*
766 gtk_text_new (GtkAdjustment *hadj,
767               GtkAdjustment *vadj)
768 {
769   GtkWidget *text;
770
771   if (hadj)
772     g_return_val_if_fail (GTK_IS_ADJUSTMENT (hadj), NULL);
773   if (vadj)
774     g_return_val_if_fail (GTK_IS_ADJUSTMENT (vadj), NULL);
775
776   text = gtk_widget_new (GTK_TYPE_TEXT,
777                          "hadjustment", hadj,
778                          "vadjustment", vadj,
779                          NULL);
780
781   return text;
782 }
783
784 void
785 gtk_text_set_word_wrap (GtkText *text,
786                         gboolean word_wrap)
787 {
788   g_return_if_fail (GTK_IS_TEXT (text));
789   
790   text->word_wrap = (word_wrap != FALSE);
791   
792   if (GTK_WIDGET_REALIZED (text))
793     {
794       recompute_geometry (text);
795       gtk_widget_queue_draw (GTK_WIDGET (text));
796     }
797   
798   g_object_notify (G_OBJECT (text), "word_wrap");
799 }
800
801 void
802 gtk_text_set_line_wrap (GtkText *text,
803                         gboolean line_wrap)
804 {
805   g_return_if_fail (GTK_IS_TEXT (text));
806   
807   text->line_wrap = (line_wrap != FALSE);
808   
809   if (GTK_WIDGET_REALIZED (text))
810     {
811       recompute_geometry (text);
812       gtk_widget_queue_draw (GTK_WIDGET (text));
813     }
814   
815   g_object_notify (G_OBJECT (text), "line_wrap");
816 }
817
818 void
819 gtk_text_set_editable (GtkText *text,
820                        gboolean is_editable)
821 {
822   g_return_if_fail (GTK_IS_TEXT (text));
823   
824   gtk_editable_set_editable (GTK_EDITABLE (text), is_editable);
825 }
826
827 static void
828 gtk_text_real_set_editable (GtkOldEditable *old_editable,
829                             gboolean        is_editable)
830 {
831   GtkText *text;
832   
833   g_return_if_fail (GTK_IS_TEXT (old_editable));
834   
835   text = GTK_TEXT (old_editable);
836   
837   old_editable->editable = (is_editable != FALSE);
838   
839   if (is_editable)
840     draw_cursor (text, TRUE);
841   else
842     undraw_cursor (text, TRUE);
843 }
844
845 void
846 gtk_text_set_adjustments (GtkText       *text,
847                           GtkAdjustment *hadj,
848                           GtkAdjustment *vadj)
849 {
850   g_return_if_fail (GTK_IS_TEXT (text));
851   if (hadj)
852     g_return_if_fail (GTK_IS_ADJUSTMENT (hadj));
853   else
854     hadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
855   if (vadj)
856     g_return_if_fail (GTK_IS_ADJUSTMENT (vadj));
857   else
858     vadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
859   
860   if (text->hadj && (text->hadj != hadj))
861     {
862       gtk_signal_disconnect_by_data (GTK_OBJECT (text->hadj), text);
863       gtk_object_unref (GTK_OBJECT (text->hadj));
864     }
865   
866   if (text->vadj && (text->vadj != vadj))
867     {
868       gtk_signal_disconnect_by_data (GTK_OBJECT (text->vadj), text);
869       gtk_object_unref (GTK_OBJECT (text->vadj));
870     }
871   
872   g_object_freeze_notify (G_OBJECT (text));
873   if (text->hadj != hadj)
874     {
875       text->hadj = hadj;
876       gtk_object_ref (GTK_OBJECT (text->hadj));
877       gtk_object_sink (GTK_OBJECT (text->hadj));
878       
879       gtk_signal_connect (GTK_OBJECT (text->hadj), "changed",
880                           (GtkSignalFunc) gtk_text_adjustment,
881                           text);
882       gtk_signal_connect (GTK_OBJECT (text->hadj), "value_changed",
883                           (GtkSignalFunc) gtk_text_adjustment,
884                           text);
885       gtk_signal_connect (GTK_OBJECT (text->hadj), "destroy",
886                           (GtkSignalFunc) gtk_text_adjustment_destroyed,
887                           text);
888       gtk_text_adjustment (hadj, text);
889
890       g_object_notify (G_OBJECT (text), "hadjustment");
891     }
892   
893   if (text->vadj != vadj)
894     {
895       text->vadj = vadj;
896       gtk_object_ref (GTK_OBJECT (text->vadj));
897       gtk_object_sink (GTK_OBJECT (text->vadj));
898       
899       gtk_signal_connect (GTK_OBJECT (text->vadj), "changed",
900                           (GtkSignalFunc) gtk_text_adjustment,
901                           text);
902       gtk_signal_connect (GTK_OBJECT (text->vadj), "value_changed",
903                           (GtkSignalFunc) gtk_text_adjustment,
904                           text);
905       gtk_signal_connect (GTK_OBJECT (text->vadj), "destroy",
906                           (GtkSignalFunc) gtk_text_adjustment_destroyed,
907                           text);
908       gtk_text_adjustment (vadj, text);
909
910       g_object_notify (G_OBJECT (text), "vadjustment");
911     }
912   g_object_thaw_notify (G_OBJECT (text));
913 }
914
915 void
916 gtk_text_set_point (GtkText *text,
917                     guint    index)
918 {
919   g_return_if_fail (GTK_IS_TEXT (text));
920   g_return_if_fail (index <= TEXT_LENGTH (text));
921   
922   text->point = find_mark (text, index);
923 }
924
925 guint
926 gtk_text_get_point (GtkText *text)
927 {
928   g_return_val_if_fail (GTK_IS_TEXT (text), 0);
929   
930   return text->point.index;
931 }
932
933 guint
934 gtk_text_get_length (GtkText *text)
935 {
936   g_return_val_if_fail (GTK_IS_TEXT (text), 0);
937   
938   return TEXT_LENGTH (text);
939 }
940
941 void
942 gtk_text_freeze (GtkText *text)
943 {
944   g_return_if_fail (GTK_IS_TEXT (text));
945   
946   text->freeze_count++;
947 }
948
949 void
950 gtk_text_thaw (GtkText *text)
951 {
952   g_return_if_fail (GTK_IS_TEXT (text));
953   
954   if (text->freeze_count)
955     if (!(--text->freeze_count) && GTK_WIDGET_REALIZED (text))
956       {
957         recompute_geometry (text);
958         gtk_widget_queue_draw (GTK_WIDGET (text));
959       }
960 }
961
962 void
963 gtk_text_insert (GtkText        *text,
964                  GdkFont        *font,
965                  const GdkColor *fore,
966                  const GdkColor *back,
967                  const char     *chars,
968                  gint            nchars)
969 {
970   GtkOldEditable *old_editable = GTK_OLD_EDITABLE (text);
971   gboolean frozen = FALSE;
972   
973   gint new_line_count = 1;
974   guint old_height = 0;
975   guint length;
976   guint i;
977   gint numwcs;
978   
979   g_return_if_fail (GTK_IS_TEXT (text));
980
981   if (nchars < 0)
982     length = strlen (chars);
983   else
984     length = nchars;
985   
986   if (length == 0)
987     return;
988   
989   if (!text->freeze_count && (length > FREEZE_LENGTH))
990     {
991       gtk_text_freeze (text);
992       frozen = TRUE;
993     }
994   
995   if (!text->freeze_count && (text->line_start_cache != NULL))
996     {
997       find_line_containing_point (text, text->point.index, TRUE);
998       old_height = total_line_height (text, text->current_line, 1);
999     }
1000   
1001   if ((TEXT_LENGTH (text) == 0) && (text->use_wchar == FALSE))
1002     {
1003       GtkWidget *widget = GTK_WIDGET (text);
1004       
1005       gtk_widget_ensure_style (widget);
1006       if ((widget->style) &&
1007           (gtk_style_get_font (widget->style)->type == GDK_FONT_FONTSET))
1008         {
1009           text->use_wchar = TRUE;
1010           g_free (text->text.ch);
1011           text->text.wc = g_new (GdkWChar, INITIAL_BUFFER_SIZE);
1012           text->text_len = INITIAL_BUFFER_SIZE;
1013           if (text->scratch_buffer.ch)
1014             g_free (text->scratch_buffer.ch);
1015           text->scratch_buffer.wc = NULL;
1016           text->scratch_buffer_len = 0;
1017         }
1018     }
1019  
1020   move_gap (text, text->point.index);
1021   make_forward_space (text, length);
1022  
1023   if (text->use_wchar)
1024     {
1025       char *chars_nt = (char *)chars;
1026       if (nchars > 0)
1027         {
1028           chars_nt = g_new (char, length+1);
1029           memcpy (chars_nt, chars, length);
1030           chars_nt[length] = 0;
1031         }
1032       numwcs = gdk_mbstowcs (text->text.wc + text->gap_position, chars_nt,
1033                              length);
1034       if (chars_nt != chars)
1035         g_free(chars_nt);
1036       if (numwcs < 0)
1037         numwcs = 0;
1038     }
1039   else
1040     {
1041       numwcs = length;
1042       memcpy(text->text.ch + text->gap_position, chars, length);
1043     }
1044  
1045   if (!text->freeze_count && (text->line_start_cache != NULL))
1046     {
1047       if (text->use_wchar)
1048         {
1049           for (i=0; i<numwcs; i++)
1050             if (text->text.wc[text->gap_position + i] == '\n')
1051               new_line_count++;
1052         }
1053       else
1054         {
1055           for (i=0; i<numwcs; i++)
1056             if (text->text.ch[text->gap_position + i] == '\n')
1057               new_line_count++;
1058         }
1059     }
1060  
1061   if (numwcs > 0)
1062     {
1063       insert_text_property (text, font, fore, back, numwcs);
1064    
1065       text->gap_size -= numwcs;
1066       text->gap_position += numwcs;
1067    
1068       if (text->point.index < text->first_line_start_index)
1069         text->first_line_start_index += numwcs;
1070       if (text->point.index < old_editable->selection_start_pos)
1071         old_editable->selection_start_pos += numwcs;
1072       if (text->point.index < old_editable->selection_end_pos)
1073         old_editable->selection_end_pos += numwcs;
1074       /* We'll reset the cursor later anyways if we aren't frozen */
1075       if (text->point.index < text->cursor_mark.index)
1076         text->cursor_mark.index += numwcs;
1077   
1078       advance_mark_n (&text->point, numwcs);
1079   
1080       if (!text->freeze_count && (text->line_start_cache != NULL))
1081         insert_expose (text, old_height, numwcs, new_line_count);
1082     }
1083
1084   if (frozen)
1085     gtk_text_thaw (text);
1086 }
1087
1088 gboolean
1089 gtk_text_backward_delete (GtkText *text,
1090                           guint    nchars)
1091 {
1092   g_return_val_if_fail (GTK_IS_TEXT (text), FALSE);
1093   
1094   if (nchars > text->point.index || nchars <= 0)
1095     return FALSE;
1096   
1097   gtk_text_set_point (text, text->point.index - nchars);
1098   
1099   return gtk_text_forward_delete (text, nchars);
1100 }
1101
1102 gboolean
1103 gtk_text_forward_delete (GtkText *text,
1104                          guint    nchars)
1105 {
1106   guint old_lines, old_height;
1107   GtkOldEditable *old_editable = GTK_OLD_EDITABLE (text);
1108   gboolean frozen = FALSE;
1109   
1110   g_return_val_if_fail (GTK_IS_TEXT (text), FALSE);
1111   
1112   if (text->point.index + nchars > TEXT_LENGTH (text) || nchars <= 0)
1113     return FALSE;
1114   
1115   if (!text->freeze_count && nchars > FREEZE_LENGTH)
1116     {
1117       gtk_text_freeze (text);
1118       frozen = TRUE;
1119     }
1120   
1121   if (!text->freeze_count && text->line_start_cache != NULL)
1122     {
1123       /* We need to undraw the cursor here, since we may later
1124        * delete the cursor's property
1125        */
1126       undraw_cursor (text, FALSE);
1127       find_line_containing_point (text, text->point.index, TRUE);
1128       compute_lines_pixels (text, nchars, &old_lines, &old_height);
1129     }
1130   
1131   /* FIXME, or resizing after deleting will be odd */
1132   if (text->point.index < text->first_line_start_index)
1133     {
1134       if (text->point.index + nchars >= text->first_line_start_index)
1135         {
1136           text->first_line_start_index = text->point.index;
1137           while ((text->first_line_start_index > 0) &&
1138                  (GTK_TEXT_INDEX (text, text->first_line_start_index - 1)
1139                   != LINE_DELIM))
1140             text->first_line_start_index -= 1;
1141           
1142         }
1143       else
1144         text->first_line_start_index -= nchars;
1145     }
1146   
1147   if (text->point.index < old_editable->selection_start_pos)
1148     old_editable->selection_start_pos -= 
1149       MIN(nchars, old_editable->selection_start_pos - text->point.index);
1150   if (text->point.index < old_editable->selection_end_pos)
1151     old_editable->selection_end_pos -= 
1152       MIN(nchars, old_editable->selection_end_pos - text->point.index);
1153   /* We'll reset the cursor later anyways if we aren't frozen */
1154   if (text->point.index < text->cursor_mark.index)
1155     move_mark_n (&text->cursor_mark, 
1156                  -MIN(nchars, text->cursor_mark.index - text->point.index));
1157   
1158   move_gap (text, text->point.index);
1159   
1160   text->gap_size += nchars;
1161   
1162   delete_text_property (text, nchars);
1163   
1164   if (!text->freeze_count && (text->line_start_cache != NULL))
1165     {
1166       delete_expose (text, nchars, old_lines, old_height);
1167       draw_cursor (text, FALSE);
1168     }
1169   
1170   if (frozen)
1171     gtk_text_thaw (text);
1172   
1173   return TRUE;
1174 }
1175
1176 static void
1177 gtk_text_set_position (GtkOldEditable *old_editable,
1178                        gint            position)
1179 {
1180   GtkText *text = (GtkText *) old_editable;
1181
1182   if (position < 0)
1183     position = gtk_text_get_length (text);                                    
1184   
1185   undraw_cursor (text, FALSE);
1186   text->cursor_mark = find_mark (text, position);
1187   find_cursor (text, TRUE);
1188   draw_cursor (text, FALSE);
1189   gtk_editable_select_region (GTK_EDITABLE (old_editable), 0, 0);
1190 }
1191
1192 static gchar *    
1193 gtk_text_get_chars (GtkOldEditable *old_editable,
1194                     gint            start_pos,
1195                     gint            end_pos)
1196 {
1197   GtkText *text;
1198
1199   gchar *retval;
1200   
1201   g_return_val_if_fail (GTK_IS_TEXT (old_editable), NULL);
1202   text = GTK_TEXT (old_editable);
1203   
1204   if (end_pos < 0)
1205     end_pos = TEXT_LENGTH (text);
1206   
1207   if ((start_pos < 0) || 
1208       (end_pos > TEXT_LENGTH (text)) || 
1209       (end_pos < start_pos))
1210     return NULL;
1211   
1212   move_gap (text, TEXT_LENGTH (text));
1213   make_forward_space (text, 1);
1214
1215   if (text->use_wchar)
1216     {
1217       GdkWChar ch;
1218       ch = text->text.wc[end_pos];
1219       text->text.wc[end_pos] = 0;
1220       retval = gdk_wcstombs (text->text.wc + start_pos);
1221       text->text.wc[end_pos] = ch;
1222     }
1223   else
1224     {
1225       guchar ch;
1226       ch = text->text.ch[end_pos];
1227       text->text.ch[end_pos] = 0;
1228       retval = g_strdup (text->text.ch + start_pos);
1229       text->text.ch[end_pos] = ch;
1230     }
1231
1232   return retval;
1233 }
1234
1235
1236 static void
1237 gtk_text_destroy (GtkObject *object)
1238 {
1239   GtkText *text;
1240   
1241   g_return_if_fail (GTK_IS_TEXT (object));
1242   
1243   text = GTK_TEXT (object);
1244
1245   if (text->hadj)
1246     {
1247       gtk_signal_disconnect_by_data (GTK_OBJECT (text->hadj), text);
1248       gtk_object_unref (GTK_OBJECT (text->hadj));
1249       text->hadj = NULL;
1250     }
1251   if (text->vadj)
1252     {
1253       gtk_signal_disconnect_by_data (GTK_OBJECT (text->vadj), text);
1254       gtk_object_unref (GTK_OBJECT (text->vadj));
1255       text->vadj = NULL;
1256     }
1257
1258   if (text->timer)
1259     {
1260       g_source_remove (text->timer);
1261       text->timer = 0;
1262     }
1263   
1264   GTK_OBJECT_CLASS(parent_class)->destroy (object);
1265 }
1266
1267 static void
1268 gtk_text_finalize (GObject *object)
1269 {
1270   GtkText *text;
1271   GList *tmp_list;
1272   
1273   g_return_if_fail (GTK_IS_TEXT (object));
1274   
1275   text = GTK_TEXT (object);
1276
1277   /* Clean up the internal structures */
1278   if (text->use_wchar)
1279     g_free (text->text.wc);
1280   else
1281     g_free (text->text.ch);
1282   
1283   tmp_list = text->text_properties;
1284   while (tmp_list)
1285     {
1286       destroy_text_property (tmp_list->data);
1287       tmp_list = tmp_list->next;
1288     }
1289
1290   if (text->current_font)
1291     text_font_unref (text->current_font);
1292   
1293   g_list_free (text->text_properties);
1294   
1295   if (text->use_wchar)
1296     {
1297       if (text->scratch_buffer.wc)
1298         g_free (text->scratch_buffer.wc);
1299     }
1300   else
1301     {
1302       if (text->scratch_buffer.ch)
1303         g_free (text->scratch_buffer.ch);
1304     }
1305   
1306   g_list_free (text->tab_stops);
1307   
1308   G_OBJECT_CLASS (parent_class)->finalize (object);
1309 }
1310
1311 static void
1312 gtk_text_realize (GtkWidget *widget)
1313 {
1314   GtkText *text;
1315   GtkOldEditable *old_editable;
1316   GdkWindowAttr attributes;
1317   gint attributes_mask;
1318   
1319   g_return_if_fail (GTK_IS_TEXT (widget));
1320   
1321   text = GTK_TEXT (widget);
1322   old_editable = GTK_OLD_EDITABLE (widget);
1323   GTK_WIDGET_SET_FLAGS (text, GTK_REALIZED);
1324   
1325   attributes.window_type = GDK_WINDOW_CHILD;
1326   attributes.x = widget->allocation.x;
1327   attributes.y = widget->allocation.y;
1328   attributes.width = widget->allocation.width;
1329   attributes.height = widget->allocation.height;
1330   attributes.wclass = GDK_INPUT_OUTPUT;
1331   attributes.visual = gtk_widget_get_visual (widget);
1332   attributes.colormap = gtk_widget_get_colormap (widget);
1333   attributes.event_mask = gtk_widget_get_events (widget);
1334   attributes.event_mask |= (GDK_EXPOSURE_MASK |
1335                             GDK_BUTTON_PRESS_MASK |
1336                             GDK_BUTTON_RELEASE_MASK |
1337                             GDK_BUTTON_MOTION_MASK |
1338                             GDK_ENTER_NOTIFY_MASK |
1339                             GDK_LEAVE_NOTIFY_MASK |
1340                             GDK_KEY_PRESS_MASK);
1341   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
1342   
1343   widget->window = gdk_window_new (gtk_widget_get_parent_window (widget), &attributes, attributes_mask);
1344   gdk_window_set_user_data (widget->window, text);
1345   
1346   attributes.x = (widget->style->xthickness + TEXT_BORDER_ROOM);
1347   attributes.y = (widget->style->ythickness + TEXT_BORDER_ROOM);
1348   attributes.width = MAX (1, (gint)widget->allocation.width - (gint)attributes.x * 2);
1349   attributes.height = MAX (1, (gint)widget->allocation.height - (gint)attributes.y * 2);
1350
1351   attributes.cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget), GDK_XTERM);
1352   attributes_mask |= GDK_WA_CURSOR;
1353   
1354   text->text_area = gdk_window_new (widget->window, &attributes, attributes_mask);
1355   gdk_window_set_user_data (text->text_area, text);
1356
1357   gdk_cursor_destroy (attributes.cursor); /* The X server will keep it around as long as necessary */
1358   
1359   widget->style = gtk_style_attach (widget->style, widget->window);
1360   
1361   /* Can't call gtk_style_set_background here because it's handled specially */
1362   gdk_window_set_background (widget->window, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1363   gdk_window_set_background (text->text_area, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1364
1365   if (widget->style->bg_pixmap[GTK_STATE_NORMAL])
1366     text->bg_gc = create_bg_gc (text);
1367   
1368   text->line_wrap_bitmap = gdk_bitmap_create_from_data (text->text_area,
1369                                                         (gchar*) line_wrap_bits,
1370                                                         line_wrap_width,
1371                                                         line_wrap_height);
1372   
1373   text->line_arrow_bitmap = gdk_bitmap_create_from_data (text->text_area,
1374                                                          (gchar*) line_arrow_bits,
1375                                                          line_arrow_width,
1376                                                          line_arrow_height);
1377   
1378   text->gc = gdk_gc_new (text->text_area);
1379   gdk_gc_set_exposures (text->gc, TRUE);
1380   gdk_gc_set_foreground (text->gc, &widget->style->text[GTK_STATE_NORMAL]);
1381   
1382   realize_properties (text);
1383   gdk_window_show (text->text_area);
1384   init_properties (text);
1385
1386   if (old_editable->selection_start_pos != old_editable->selection_end_pos)
1387     gtk_old_editable_claim_selection (old_editable, TRUE, GDK_CURRENT_TIME);
1388   
1389   recompute_geometry (text);
1390 }
1391
1392 static void 
1393 gtk_text_style_set (GtkWidget *widget,
1394                     GtkStyle  *previous_style)
1395 {
1396   GtkText *text = GTK_TEXT (widget);
1397
1398   if (GTK_WIDGET_REALIZED (widget))
1399     {
1400       gdk_window_set_background (widget->window, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1401       gdk_window_set_background (text->text_area, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1402       
1403       if (text->bg_gc)
1404         {
1405           gdk_gc_destroy (text->bg_gc);
1406           text->bg_gc = NULL;
1407         }
1408
1409       if (widget->style->bg_pixmap[GTK_STATE_NORMAL])
1410         text->bg_gc = create_bg_gc (text);
1411
1412       recompute_geometry (text);
1413     }
1414   
1415   if (text->current_font)
1416     text_font_unref (text->current_font);
1417   text->current_font = get_text_font (gtk_style_get_font (widget->style));
1418 }
1419
1420 static void
1421 gtk_text_state_changed (GtkWidget   *widget,
1422                         GtkStateType previous_state)
1423 {
1424   GtkText *text = GTK_TEXT (widget);
1425   
1426   if (GTK_WIDGET_REALIZED (widget))
1427     {
1428       gdk_window_set_background (widget->window, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1429       gdk_window_set_background (text->text_area, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1430     }
1431 }
1432
1433 static void
1434 gtk_text_unrealize (GtkWidget *widget)
1435 {
1436   GtkText *text;
1437   
1438   g_return_if_fail (GTK_IS_TEXT (widget));
1439   
1440   text = GTK_TEXT (widget);
1441
1442   gdk_window_set_user_data (text->text_area, NULL);
1443   gdk_window_destroy (text->text_area);
1444   text->text_area = NULL;
1445   
1446   gdk_gc_destroy (text->gc);
1447   text->gc = NULL;
1448
1449   if (text->bg_gc)
1450     {
1451       gdk_gc_destroy (text->bg_gc);
1452       text->bg_gc = NULL;
1453     }
1454   
1455   gdk_pixmap_unref (text->line_wrap_bitmap);
1456   gdk_pixmap_unref (text->line_arrow_bitmap);
1457
1458   unrealize_properties (text);
1459
1460   free_cache (text);
1461
1462   if (GTK_WIDGET_CLASS (parent_class)->unrealize)
1463     (* GTK_WIDGET_CLASS (parent_class)->unrealize) (widget);
1464 }
1465
1466 static void
1467 clear_focus_area (GtkText *text, gint area_x, gint area_y, gint area_width, gint area_height)
1468 {
1469   GtkWidget *widget = GTK_WIDGET (text);
1470   GdkGC *gc;
1471  
1472   gint ythick = TEXT_BORDER_ROOM + widget->style->ythickness;
1473   gint xthick = TEXT_BORDER_ROOM + widget->style->xthickness;
1474   
1475   gint width, height;
1476   
1477   if (area_width == 0 || area_height == 0)
1478     return;
1479     
1480   if (widget->style->bg_pixmap[GTK_STATE_NORMAL])
1481     {
1482       gdk_window_get_size (widget->style->bg_pixmap[GTK_STATE_NORMAL], &width, &height);
1483   
1484       gdk_gc_set_ts_origin (text->bg_gc,
1485                             (- text->first_onscreen_hor_pixel + xthick) % width,
1486                             (- text->first_onscreen_ver_pixel + ythick) % height);
1487       
1488        gc = text->bg_gc;
1489     }
1490   else
1491     gc = widget->style->base_gc[widget->state];
1492
1493   gdk_draw_rectangle (GTK_WIDGET (text)->window, gc, TRUE,
1494                       area_x, area_y, area_width, area_height);
1495 }
1496
1497 static void
1498 gtk_text_draw_focus (GtkWidget *widget)
1499 {
1500   GtkText *text;
1501   gint width, height;
1502   gint x, y;
1503   
1504   g_return_if_fail (GTK_IS_TEXT (widget));
1505   
1506   text = GTK_TEXT (widget);
1507   
1508   if (GTK_WIDGET_DRAWABLE (widget))
1509     {
1510       gint ythick = widget->style->ythickness;
1511       gint xthick = widget->style->xthickness;
1512       gint xextra = TEXT_BORDER_ROOM;
1513       gint yextra = TEXT_BORDER_ROOM;
1514       
1515       TDEBUG (("in gtk_text_draw_focus\n"));
1516       
1517       x = 0;
1518       y = 0;
1519       width = widget->allocation.width;
1520       height = widget->allocation.height;
1521       
1522       if (GTK_WIDGET_HAS_FOCUS (widget))
1523         {
1524           x += 1;
1525           y += 1;
1526           width -=  2;
1527           height -= 2;
1528           xextra -= 1;
1529           yextra -= 1;
1530
1531           gtk_paint_focus (widget->style, widget->window, GTK_WIDGET_STATE (widget),
1532                            NULL, widget, "text",
1533                            0, 0,
1534                            widget->allocation.width,
1535                            widget->allocation.height);
1536         }
1537
1538       gtk_paint_shadow (widget->style, widget->window,
1539                         GTK_STATE_NORMAL, GTK_SHADOW_IN,
1540                         NULL, widget, "text",
1541                         x, y, width, height);
1542
1543       x += xthick; 
1544       y += ythick;
1545       width -= 2 * xthick;
1546       height -= 2 * ythick;
1547       
1548       /* top rect */
1549       clear_focus_area (text, x, y, width, yextra);
1550       /* left rect */
1551       clear_focus_area (text, x, y + yextra, 
1552                         xextra, y + height - 2 * yextra);
1553       /* right rect */
1554       clear_focus_area (text, x + width - xextra, y + yextra, 
1555                         xextra, height - 2 * ythick);
1556       /* bottom rect */
1557       clear_focus_area (text, x, x + height - yextra, width, yextra);
1558     }
1559   else
1560     {
1561       TDEBUG (("in gtk_text_draw_focus (undrawable !!!)\n"));
1562     }
1563 }
1564
1565 static void
1566 gtk_text_size_request (GtkWidget      *widget,
1567                        GtkRequisition *requisition)
1568 {
1569   GdkFont *font;
1570   gint xthickness;
1571   gint ythickness;
1572   gint char_height;
1573   gint char_width;
1574   
1575   g_return_if_fail (GTK_IS_TEXT (widget));
1576   g_return_if_fail (requisition != NULL);
1577   
1578   xthickness = widget->style->xthickness + TEXT_BORDER_ROOM;
1579   ythickness = widget->style->ythickness + TEXT_BORDER_ROOM;
1580
1581   font = gtk_style_get_font (widget->style);
1582   
1583   char_height = MIN_TEXT_HEIGHT_LINES * (font->ascent +
1584                                          font->descent);
1585   
1586   char_width = MIN_TEXT_WIDTH_LINES * (gdk_text_width (font,
1587                                                        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
1588                                                        26)
1589                                        / 26);
1590   
1591   requisition->width  = char_width  + xthickness * 2;
1592   requisition->height = char_height + ythickness * 2;
1593 }
1594
1595 static void
1596 gtk_text_size_allocate (GtkWidget     *widget,
1597                         GtkAllocation *allocation)
1598 {
1599   GtkText *text;
1600   GtkOldEditable *old_editable;
1601   
1602   g_return_if_fail (GTK_IS_TEXT (widget));
1603   g_return_if_fail (allocation != NULL);
1604   
1605   text = GTK_TEXT (widget);
1606   old_editable = GTK_OLD_EDITABLE (widget);
1607   
1608   widget->allocation = *allocation;
1609   if (GTK_WIDGET_REALIZED (widget))
1610     {
1611       gdk_window_move_resize (widget->window,
1612                               allocation->x, allocation->y,
1613                               allocation->width, allocation->height);
1614       
1615       gdk_window_move_resize (text->text_area,
1616                               widget->style->xthickness + TEXT_BORDER_ROOM,
1617                               widget->style->ythickness + TEXT_BORDER_ROOM,
1618                               MAX (1, (gint)widget->allocation.width - (gint)(widget->style->xthickness +
1619                                                           (gint)TEXT_BORDER_ROOM) * 2),
1620                               MAX (1, (gint)widget->allocation.height - (gint)(widget->style->ythickness +
1621                                                            (gint)TEXT_BORDER_ROOM) * 2));
1622       
1623       recompute_geometry (text);
1624     }
1625 }
1626
1627 static gint
1628 gtk_text_expose (GtkWidget      *widget,
1629                  GdkEventExpose *event)
1630 {
1631   g_return_val_if_fail (GTK_IS_TEXT (widget), FALSE);
1632   g_return_val_if_fail (event != NULL, FALSE);
1633   
1634   if (event->window == GTK_TEXT (widget)->text_area)
1635     {
1636       TDEBUG (("in gtk_text_expose (expose)\n"));
1637       expose_text (GTK_TEXT (widget), &event->area, TRUE);
1638     }
1639   else if (event->count == 0)
1640     {
1641       TDEBUG (("in gtk_text_expose (focus)\n"));
1642       gtk_text_draw_focus (widget);
1643     }
1644   
1645   return FALSE;
1646 }
1647
1648 static gint
1649 gtk_text_scroll_timeout (gpointer data)
1650 {
1651   GtkText *text;
1652   gint x, y;
1653   GdkModifierType mask;
1654   
1655   GDK_THREADS_ENTER ();
1656
1657   text = GTK_TEXT (data);
1658   
1659   text->timer = 0;
1660   gdk_window_get_pointer (text->text_area, &x, &y, &mask);
1661   
1662   if (mask & (GDK_BUTTON1_MASK | GDK_BUTTON3_MASK))
1663     {
1664       GdkEvent *event = gdk_event_new (GDK_MOTION_NOTIFY);
1665       
1666       event->motion.is_hint = 0;
1667       event->motion.x = x;
1668       event->motion.y = y;
1669       event->motion.state = mask;
1670       
1671       gtk_text_motion_notify (GTK_WIDGET (text), (GdkEventMotion *)event);
1672
1673       gdk_event_free (event);
1674     }
1675
1676   GDK_THREADS_LEAVE ();
1677   
1678   return FALSE;
1679 }
1680
1681 static gint
1682 gtk_text_button_press (GtkWidget      *widget,
1683                        GdkEventButton *event)
1684 {
1685   GtkText *text;
1686   GtkOldEditable *old_editable;
1687   
1688   g_return_val_if_fail (GTK_IS_TEXT (widget), FALSE);
1689   g_return_val_if_fail (event != NULL, FALSE);
1690   
1691   text = GTK_TEXT (widget);
1692   old_editable = GTK_OLD_EDITABLE (widget);
1693   
1694   if (text->button && (event->button != text->button))
1695     return FALSE;
1696   
1697   text->button = event->button;
1698   
1699   if (!GTK_WIDGET_HAS_FOCUS (widget))
1700     gtk_widget_grab_focus (widget);
1701   
1702   if (event->button == 1)
1703     {
1704       switch (event->type)
1705         {
1706         case GDK_BUTTON_PRESS:
1707           gtk_grab_add (widget);
1708           
1709           undraw_cursor (text, FALSE);
1710           find_mouse_cursor (text, (gint)event->x, (gint)event->y);
1711           draw_cursor (text, FALSE);
1712           
1713           /* Set it now, so we display things right. We'll unset it
1714            * later if things don't work out */
1715           old_editable->has_selection = TRUE;
1716           gtk_text_set_selection (GTK_OLD_EDITABLE (text),
1717                                   text->cursor_mark.index,
1718                                   text->cursor_mark.index);
1719           
1720           break;
1721           
1722         case GDK_2BUTTON_PRESS:
1723           gtk_text_select_word (text, event->time);
1724           break;
1725           
1726         case GDK_3BUTTON_PRESS:
1727           gtk_text_select_line (text, event->time);
1728           break;
1729           
1730         default:
1731           break;
1732         }
1733     }
1734   else if (event->type == GDK_BUTTON_PRESS)
1735     {
1736       if ((event->button == 2) && old_editable->editable)
1737         {
1738           if (old_editable->selection_start_pos == old_editable->selection_end_pos ||
1739               old_editable->has_selection)
1740             {
1741               undraw_cursor (text, FALSE);
1742               find_mouse_cursor (text, (gint)event->x, (gint)event->y);
1743               draw_cursor (text, FALSE);
1744               
1745             }
1746           
1747           gtk_selection_convert (widget, GDK_SELECTION_PRIMARY,
1748                                  gdk_atom_intern ("UTF8_STRING", FALSE),
1749                                  event->time);
1750         }
1751       else
1752         {
1753           GdkDisplay *display = gtk_widget_get_display (widget);
1754           
1755           gtk_grab_add (widget);
1756           
1757           undraw_cursor (text, FALSE);
1758           find_mouse_cursor (text, event->x, event->y);
1759           draw_cursor (text, FALSE);
1760           
1761           gtk_text_set_selection (GTK_OLD_EDITABLE (text),
1762                                   text->cursor_mark.index,
1763                                   text->cursor_mark.index);
1764           
1765           old_editable->has_selection = FALSE;
1766           if (gdk_selection_owner_get_for_display (display,
1767                                                    GDK_SELECTION_PRIMARY) == widget->window)
1768             gtk_selection_owner_set_for_display (display,
1769                                                  NULL, 
1770                                                  GDK_SELECTION_PRIMARY,
1771                                                  event->time);
1772         }
1773     }
1774   
1775   return TRUE;
1776 }
1777
1778 static gint
1779 gtk_text_button_release (GtkWidget      *widget,
1780                          GdkEventButton *event)
1781 {
1782   GtkText *text;
1783   GtkOldEditable *old_editable;
1784   GdkDisplay *display;
1785
1786   g_return_val_if_fail (GTK_IS_TEXT (widget), FALSE);
1787   g_return_val_if_fail (event != NULL, FALSE);
1788   
1789   text = GTK_TEXT (widget);
1790   
1791   gtk_grab_remove (widget);
1792   
1793   if (text->button != event->button)
1794     return FALSE;
1795   
1796   text->button = 0;
1797   
1798   if (text->timer)
1799     {
1800       g_source_remove (text->timer);
1801       text->timer = 0;
1802     }
1803   
1804   if (event->button == 1)
1805     {
1806       text = GTK_TEXT (widget);
1807       old_editable = GTK_OLD_EDITABLE (widget);
1808       display = gtk_widget_get_display (widget);
1809       
1810       gtk_grab_remove (widget);
1811       
1812       old_editable->has_selection = FALSE;
1813       if (old_editable->selection_start_pos != old_editable->selection_end_pos)
1814         {
1815           if (gtk_selection_owner_set_for_display (display,
1816                                                    widget,
1817                                                    GDK_SELECTION_PRIMARY,
1818                                                    event->time))
1819             old_editable->has_selection = TRUE;
1820           else
1821             gtk_text_update_text (old_editable, old_editable->selection_start_pos,
1822                                   old_editable->selection_end_pos);
1823         }
1824       else
1825         {
1826           if (gdk_selection_owner_get_for_display (display,
1827                                                    GDK_SELECTION_PRIMARY) == widget->window)
1828             gtk_selection_owner_set_for_display (display, 
1829                                                  NULL,
1830                                                  GDK_SELECTION_PRIMARY, 
1831                                                  event->time);
1832         }
1833     }
1834   else if (event->button == 3)
1835     {
1836       gtk_grab_remove (widget);
1837     }
1838   
1839   undraw_cursor (text, FALSE);
1840   find_cursor (text, TRUE);
1841   draw_cursor (text, FALSE);
1842   
1843   return TRUE;
1844 }
1845
1846 static gint
1847 gtk_text_motion_notify (GtkWidget      *widget,
1848                         GdkEventMotion *event)
1849 {
1850   GtkText *text;
1851   gint x, y;
1852   gint height;
1853   GdkModifierType mask;
1854   
1855   g_return_val_if_fail (GTK_IS_TEXT (widget), FALSE);
1856   g_return_val_if_fail (event != NULL, FALSE);
1857   
1858   text = GTK_TEXT (widget);
1859   
1860   x = event->x;
1861   y = event->y;
1862   mask = event->state;
1863   if (event->is_hint || (text->text_area != event->window))
1864     {
1865       gdk_window_get_pointer (text->text_area, &x, &y, &mask);
1866     }
1867   
1868   if ((text->button == 0) ||
1869       !(mask & (GDK_BUTTON1_MASK | GDK_BUTTON3_MASK)))
1870     return FALSE;
1871   
1872   gdk_window_get_size (text->text_area, NULL, &height);
1873   
1874   if ((y < 0) || (y > height))
1875     {
1876       if (text->timer == 0)
1877         {
1878           text->timer = g_timeout_add (SCROLL_TIME, 
1879                                        gtk_text_scroll_timeout,
1880                                        text);
1881           
1882           if (y < 0)
1883             scroll_int (text, y/2);
1884           else
1885             scroll_int (text, (y - height)/2);
1886         }
1887       else
1888         return FALSE;
1889     }
1890   
1891   undraw_cursor (GTK_TEXT (widget), FALSE);
1892   find_mouse_cursor (GTK_TEXT (widget), x, y);
1893   draw_cursor (GTK_TEXT (widget), FALSE);
1894   
1895   gtk_text_set_selection (GTK_OLD_EDITABLE (text), 
1896                           GTK_OLD_EDITABLE (text)->selection_start_pos,
1897                           text->cursor_mark.index);
1898   
1899   return FALSE;
1900 }
1901
1902 static void 
1903 gtk_text_insert_text    (GtkEditable       *editable,
1904                          const gchar       *new_text,
1905                          gint               new_text_length,
1906                          gint              *position)
1907 {
1908   GtkText *text = GTK_TEXT (editable);
1909   GdkFont *font;
1910   GdkColor *fore, *back;
1911
1912   TextProperty *property;
1913
1914   gtk_text_set_point (text, *position);
1915
1916   property = MARK_CURRENT_PROPERTY (&text->point);
1917   font = property->flags & PROPERTY_FONT ? property->font->gdk_font : NULL; 
1918   fore = property->flags & PROPERTY_FOREGROUND ? &property->fore_color : NULL; 
1919   back = property->flags & PROPERTY_BACKGROUND ? &property->back_color : NULL; 
1920   
1921   gtk_text_insert (text, font, fore, back, new_text, new_text_length);
1922
1923   *position = text->point.index;
1924 }
1925
1926 static void 
1927 gtk_text_delete_text    (GtkEditable       *editable,
1928                          gint               start_pos,
1929                          gint               end_pos)
1930 {
1931   GtkText *text;
1932   
1933   g_return_if_fail (start_pos >= 0);
1934   
1935   text = GTK_TEXT (editable);
1936   
1937   gtk_text_set_point (text, start_pos);
1938   if (end_pos < 0)
1939     end_pos = TEXT_LENGTH (text);
1940   
1941   if (end_pos > start_pos)
1942     gtk_text_forward_delete (text, end_pos - start_pos);
1943 }
1944
1945 static gint
1946 gtk_text_key_press (GtkWidget   *widget,
1947                     GdkEventKey *event)
1948 {
1949   GtkText *text;
1950   GtkOldEditable *old_editable;
1951   gchar key;
1952   gint return_val;
1953   gint position;
1954   
1955   g_return_val_if_fail (GTK_IS_TEXT (widget), FALSE);
1956   g_return_val_if_fail (event != NULL, FALSE);
1957   
1958   text = GTK_TEXT (widget);
1959   old_editable = GTK_OLD_EDITABLE (widget);
1960   
1961   key = event->keyval;
1962   return_val = TRUE;
1963   
1964   if ((GTK_OLD_EDITABLE(text)->editable == FALSE))
1965     {
1966       switch (event->keyval)
1967         {
1968         case GDK_Home:
1969         case GDK_KP_Home:
1970           if (event->state & GDK_CONTROL_MASK)
1971             scroll_int (text, -text->vadj->value);
1972           else
1973             return_val = FALSE;
1974           break;
1975         case GDK_End:
1976         case GDK_KP_End:
1977           if (event->state & GDK_CONTROL_MASK)
1978             scroll_int (text, +text->vadj->upper); 
1979           else
1980             return_val = FALSE;
1981           break;
1982         case GDK_KP_Page_Up:
1983         case GDK_Page_Up:   scroll_int (text, -text->vadj->page_increment); break;
1984         case GDK_KP_Page_Down:
1985         case GDK_Page_Down: scroll_int (text, +text->vadj->page_increment); break;
1986         case GDK_KP_Up:
1987         case GDK_Up:        scroll_int (text, -KEY_SCROLL_PIXELS); break;
1988         case GDK_KP_Down:
1989         case GDK_Down:      scroll_int (text, +KEY_SCROLL_PIXELS); break;
1990         case GDK_Return:
1991         case GDK_KP_Enter:
1992           if (event->state & GDK_CONTROL_MASK)
1993             gtk_signal_emit_by_name (GTK_OBJECT (text), "activate");
1994           else
1995             return_val = FALSE;
1996           break;
1997         default:
1998           return_val = FALSE;
1999           break;
2000         }
2001     }
2002   else
2003     {
2004       gint extend_selection;
2005       gint extend_start;
2006       guint initial_pos = old_editable->current_pos;
2007       
2008       text->point = find_mark (text, text->cursor_mark.index);
2009       
2010       extend_selection = event->state & GDK_SHIFT_MASK;
2011       extend_start = FALSE;
2012       
2013       if (extend_selection)
2014         {
2015           old_editable->has_selection = TRUE;
2016           
2017           if (old_editable->selection_start_pos == old_editable->selection_end_pos)
2018             {
2019               old_editable->selection_start_pos = text->point.index;
2020               old_editable->selection_end_pos = text->point.index;
2021             }
2022           
2023           extend_start = (text->point.index == old_editable->selection_start_pos);
2024         }
2025       
2026       switch (event->keyval)
2027         {
2028         case GDK_KP_Home:
2029         case GDK_Home:
2030           if (event->state & GDK_CONTROL_MASK)
2031             move_cursor_buffer_ver (text, -1);
2032           else
2033             gtk_text_move_beginning_of_line (text);
2034           break;
2035         case GDK_KP_End:
2036         case GDK_End:
2037           if (event->state & GDK_CONTROL_MASK)
2038             move_cursor_buffer_ver (text, +1);
2039           else
2040             gtk_text_move_end_of_line (text);
2041           break;
2042         case GDK_KP_Page_Up:
2043         case GDK_Page_Up:   move_cursor_page_ver (text, -1); break;
2044         case GDK_KP_Page_Down:
2045         case GDK_Page_Down: move_cursor_page_ver (text, +1); break;
2046           /* CUA has Ctrl-Up/Ctrl-Down as paragraph up down */
2047         case GDK_KP_Up:
2048         case GDK_Up:        move_cursor_ver (text, -1); break;
2049         case GDK_KP_Down:
2050         case GDK_Down:      move_cursor_ver (text, +1); break;
2051         case GDK_KP_Left:
2052         case GDK_Left:
2053           if (event->state & GDK_CONTROL_MASK)
2054             gtk_text_move_backward_word (text);
2055           else
2056             move_cursor_hor (text, -1); 
2057           break;
2058         case GDK_KP_Right:
2059         case GDK_Right:     
2060           if (event->state & GDK_CONTROL_MASK)
2061             gtk_text_move_forward_word (text);
2062           else
2063             move_cursor_hor (text, +1); 
2064           break;
2065           
2066         case GDK_BackSpace:
2067           if (event->state & GDK_CONTROL_MASK)
2068             gtk_text_delete_backward_word (text);
2069           else
2070             gtk_text_delete_backward_character (text);
2071           break;
2072         case GDK_Clear:
2073           gtk_text_delete_line (text);
2074           break;
2075         case GDK_KP_Insert:
2076         case GDK_Insert:
2077           if (event->state & GDK_SHIFT_MASK)
2078             {
2079               extend_selection = FALSE;
2080               gtk_editable_paste_clipboard (GTK_EDITABLE (old_editable));
2081             }
2082           else if (event->state & GDK_CONTROL_MASK)
2083             {
2084               gtk_editable_copy_clipboard (GTK_EDITABLE (old_editable));
2085             }
2086           else
2087             {
2088               /* gtk_toggle_insert(text) -- IMPLEMENT */
2089             }
2090           break;
2091         case GDK_Delete:
2092         case GDK_KP_Delete:
2093           if (event->state & GDK_CONTROL_MASK)
2094             gtk_text_delete_forward_word (text);
2095           else if (event->state & GDK_SHIFT_MASK)
2096             {
2097               extend_selection = FALSE;
2098               gtk_editable_cut_clipboard (GTK_EDITABLE (old_editable));
2099             }
2100           else
2101             gtk_text_delete_forward_character (text);
2102           break;
2103         case GDK_Tab:
2104         case GDK_ISO_Left_Tab:
2105         case GDK_KP_Tab:
2106           position = text->point.index;
2107           gtk_editable_insert_text (GTK_EDITABLE (old_editable), "\t", 1, &position);
2108           break;
2109         case GDK_KP_Enter:
2110         case GDK_Return:
2111           if (event->state & GDK_CONTROL_MASK)
2112             gtk_signal_emit_by_name (GTK_OBJECT (text), "activate");
2113           else
2114             {
2115               position = text->point.index;
2116               gtk_editable_insert_text (GTK_EDITABLE (old_editable), "\n", 1, &position);
2117             }
2118           break;
2119         case GDK_Escape:
2120           /* Don't insert literally */
2121           return_val = FALSE;
2122           break;
2123           
2124         default:
2125           return_val = FALSE;
2126           
2127           if (event->state & GDK_CONTROL_MASK)
2128             {
2129               if ((key >= 'A') && (key <= 'Z'))
2130                 key -= 'A' - 'a';
2131               
2132               if ((key >= 'a') && (key <= 'z') && control_keys[(int) (key - 'a')])
2133                 {
2134                   (* control_keys[(int) (key - 'a')]) (old_editable, event->time);
2135                   return_val = TRUE;
2136                 }
2137               
2138               break;
2139             }
2140           else if (event->state & GDK_MOD1_MASK)
2141             {
2142               if ((key >= 'A') && (key <= 'Z'))
2143                 key -= 'A' - 'a';
2144               
2145               if ((key >= 'a') && (key <= 'z') && alt_keys[(int) (key - 'a')])
2146                 {
2147                   (* alt_keys[(int) (key - 'a')]) (old_editable, event->time);
2148                   return_val = TRUE;
2149                 }
2150               
2151               break;
2152             }
2153           else if (event->length > 0)
2154             {
2155               extend_selection = FALSE;
2156               
2157               gtk_editable_delete_selection (GTK_EDITABLE (old_editable));
2158               position = text->point.index;
2159               gtk_editable_insert_text (GTK_EDITABLE (old_editable), event->string, event->length, &position);
2160               
2161               return_val = TRUE;
2162             }
2163         }
2164       
2165       if (return_val && (old_editable->current_pos != initial_pos))
2166         {
2167           if (extend_selection)
2168             {
2169               if (old_editable->current_pos < old_editable->selection_start_pos)
2170                 gtk_text_set_selection (old_editable, old_editable->current_pos,
2171                                         old_editable->selection_end_pos);
2172               else if (old_editable->current_pos > old_editable->selection_end_pos)
2173                 gtk_text_set_selection (old_editable, old_editable->selection_start_pos,
2174                                         old_editable->current_pos);
2175               else
2176                 {
2177                   if (extend_start)
2178                     gtk_text_set_selection (old_editable, old_editable->current_pos,
2179                                             old_editable->selection_end_pos);
2180                   else
2181                     gtk_text_set_selection (old_editable, old_editable->selection_start_pos,
2182                                             old_editable->current_pos);
2183                 }
2184             }
2185           else
2186             gtk_text_set_selection (old_editable, 0, 0);
2187           
2188           gtk_old_editable_claim_selection (old_editable,
2189                                             old_editable->selection_start_pos != old_editable->selection_end_pos,
2190                                             event->time);
2191         }
2192     }
2193   
2194   return return_val;
2195 }
2196
2197 static void
2198 gtk_text_adjustment (GtkAdjustment *adjustment,
2199                      GtkText       *text)
2200 {
2201   g_return_if_fail (GTK_IS_ADJUSTMENT (adjustment));
2202   g_return_if_fail (GTK_IS_TEXT (text));
2203   
2204   /* Just ignore it if we haven't been size-allocated and realized yet */
2205   if (text->line_start_cache == NULL) 
2206     return;
2207   
2208   if (adjustment == text->hadj)
2209     {
2210       g_warning ("horizontal scrolling not implemented");
2211     }
2212   else
2213     {
2214       gint diff = ((gint)adjustment->value) - text->last_ver_value;
2215       
2216       if (diff != 0)
2217         {
2218           undraw_cursor (text, FALSE);
2219           
2220           if (diff > 0)
2221             scroll_down (text, diff);
2222           else /* if (diff < 0) */
2223             scroll_up (text, diff);
2224           
2225           draw_cursor (text, FALSE);
2226           
2227           text->last_ver_value = adjustment->value;
2228         }
2229     }
2230 }
2231
2232 static void
2233 gtk_text_adjustment_destroyed (GtkAdjustment *adjustment,
2234                                GtkText       *text)
2235 {
2236   g_return_if_fail (GTK_IS_ADJUSTMENT (adjustment));
2237   g_return_if_fail (GTK_IS_TEXT (text));
2238
2239   if (adjustment == text->hadj)
2240     gtk_text_set_adjustments (text, NULL, text->vadj);
2241   if (adjustment == text->vadj)
2242     gtk_text_set_adjustments (text, text->hadj, NULL);
2243 }
2244
2245
2246 static GtkPropertyMark
2247 find_this_line_start_mark (GtkText* text, guint point_position, const GtkPropertyMark* near)
2248 {
2249   GtkPropertyMark mark;
2250   
2251   mark = find_mark_near (text, point_position, near);
2252   
2253   while (mark.index > 0 &&
2254          GTK_TEXT_INDEX (text, mark.index - 1) != LINE_DELIM)
2255     decrement_mark (&mark);
2256   
2257   return mark;
2258 }
2259
2260 static void
2261 init_tab_cont (GtkText* text, PrevTabCont* tab_cont)
2262 {
2263   tab_cont->pixel_offset          = 0;
2264   tab_cont->tab_start.tab_stops   = text->tab_stops;
2265   tab_cont->tab_start.to_next_tab = (gulong) text->tab_stops->data;
2266   
2267   if (!tab_cont->tab_start.to_next_tab)
2268     tab_cont->tab_start.to_next_tab = text->default_tab_width;
2269 }
2270
2271 static void
2272 line_params_iterate (GtkText* text,
2273                      const GtkPropertyMark* mark0,
2274                      const PrevTabCont* tab_mark0,
2275                      gint8 alloc,
2276                      void* data,
2277                      LineIteratorFunction iter)
2278      /* mark0 MUST be a real line start.  if ALLOC, allocate line params
2279       * from a mem chunk.  DATA is passed to ITER_CALL, which is called
2280       * for each line following MARK, iteration continues unless ITER_CALL
2281       * returns TRUE. */
2282 {
2283   GtkPropertyMark mark = *mark0;
2284   PrevTabCont  tab_conts[2];
2285   LineParams   *lp, lpbuf;
2286   gint         tab_cont_index = 0;
2287   
2288   if (tab_mark0)
2289     tab_conts[0] = *tab_mark0;
2290   else
2291     init_tab_cont (text, tab_conts);
2292   
2293   for (;;)
2294     {
2295       if (alloc)
2296         lp = g_chunk_new (LineParams, params_mem_chunk);
2297       else
2298         lp = &lpbuf;
2299       
2300       *lp = find_line_params (text, &mark, tab_conts + tab_cont_index,
2301                               tab_conts + (tab_cont_index + 1) % 2);
2302       
2303       if ((*iter) (text, lp, data))
2304         return;
2305       
2306       if (LAST_INDEX (text, lp->end))
2307         break;
2308       
2309       mark = lp->end;
2310       advance_mark (&mark);
2311       tab_cont_index = (tab_cont_index + 1) % 2;
2312     }
2313 }
2314
2315 static gint
2316 fetch_lines_iterator (GtkText* text, LineParams* lp, void* data)
2317 {
2318   FetchLinesData *fldata = (FetchLinesData*) data;
2319   
2320   fldata->new_lines = g_list_prepend (fldata->new_lines, lp);
2321   
2322   switch (fldata->fl_type)
2323     {
2324     case FetchLinesCount:
2325       if (!text->line_wrap || !lp->wraps)
2326         fldata->data += 1;
2327       
2328       if (fldata->data >= fldata->data_max)
2329         return TRUE;
2330       
2331       break;
2332     case FetchLinesPixels:
2333       
2334       fldata->data += LINE_HEIGHT(*lp);
2335       
2336       if (fldata->data >= fldata->data_max)
2337         return TRUE;
2338       
2339       break;
2340     }
2341   
2342   return FALSE;
2343 }
2344
2345 static GList*
2346 fetch_lines (GtkText* text,
2347              const GtkPropertyMark* mark0,
2348              const PrevTabCont* tab_cont0,
2349              FLType fl_type,
2350              gint data)
2351 {
2352   FetchLinesData fl_data;
2353   
2354   fl_data.new_lines = NULL;
2355   fl_data.data      = 0;
2356   fl_data.data_max  = data;
2357   fl_data.fl_type   = fl_type;
2358   
2359   line_params_iterate (text, mark0, tab_cont0, TRUE, &fl_data, fetch_lines_iterator);
2360   
2361   return g_list_reverse (fl_data.new_lines);
2362 }
2363
2364 static void
2365 fetch_lines_backward (GtkText* text)
2366 {
2367   GList* new_lines = NULL, *new_line_start;
2368   GtkPropertyMark mark;
2369   
2370   if (CACHE_DATA(text->line_start_cache).start.index == 0)
2371     return;
2372   
2373   mark = find_this_line_start_mark (text,
2374                                     CACHE_DATA(text->line_start_cache).start.index - 1,
2375                                     &CACHE_DATA(text->line_start_cache).start);
2376   
2377   new_line_start = new_lines = fetch_lines (text, &mark, NULL, FetchLinesCount, 1);
2378   
2379   while (new_line_start->next)
2380     new_line_start = new_line_start->next;
2381   
2382   new_line_start->next = text->line_start_cache;
2383   text->line_start_cache->prev = new_line_start;
2384 }
2385
2386 static void
2387 fetch_lines_forward (GtkText* text, gint line_count)
2388 {
2389   GtkPropertyMark mark;
2390   GList* line = text->line_start_cache;
2391   
2392   while(line->next)
2393     line = line->next;
2394   
2395   mark = CACHE_DATA(line).end;
2396   
2397   if (LAST_INDEX (text, mark))
2398     return;
2399   
2400   advance_mark(&mark);
2401   
2402   line->next = fetch_lines (text, &mark, &CACHE_DATA(line).tab_cont_next, FetchLinesCount, line_count);
2403   
2404   if (line->next)
2405     line->next->prev = line;
2406 }
2407
2408 /* Compute the number of lines, and vertical pixels for n characters
2409  * starting from the point 
2410  */
2411 static void
2412 compute_lines_pixels (GtkText* text, guint char_count,
2413                       guint *lines, guint *pixels)
2414 {
2415   GList *line = text->current_line;
2416   gint chars_left = char_count;
2417   
2418   *lines = 0;
2419   *pixels = 0;
2420   
2421   /* If chars_left == 0, that means we're joining two lines in a
2422    * deletion, so add in the values for the next line as well 
2423    */
2424   for (; line && chars_left >= 0; line = line->next)
2425     {
2426       *pixels += LINE_HEIGHT(CACHE_DATA(line));
2427       
2428       if (line == text->current_line)
2429         chars_left -= CACHE_DATA(line).end.index - text->point.index + 1;
2430       else
2431         chars_left -= CACHE_DATA(line).end.index - CACHE_DATA(line).start.index + 1;
2432       
2433       if (!text->line_wrap || !CACHE_DATA(line).wraps)
2434         *lines += 1;
2435       else
2436         if (chars_left < 0)
2437           chars_left = 0;       /* force another loop */
2438       
2439       if (!line->next)
2440         fetch_lines_forward (text, 1);
2441     }
2442 }
2443
2444 static gint
2445 total_line_height (GtkText* text, GList* line, gint line_count)
2446 {
2447   gint height = 0;
2448   
2449   for (; line && line_count > 0; line = line->next)
2450     {
2451       height += LINE_HEIGHT(CACHE_DATA(line));
2452       
2453       if (!text->line_wrap || !CACHE_DATA(line).wraps)
2454         line_count -= 1;
2455       
2456       if (!line->next)
2457         fetch_lines_forward (text, line_count);
2458     }
2459   
2460   return height;
2461 }
2462
2463 static void
2464 swap_lines (GtkText* text, GList* old, GList* new, guint old_line_count)
2465 {
2466   if (old == text->line_start_cache)
2467     {
2468       GList* last;
2469       
2470       for (; old_line_count > 0; old_line_count -= 1)
2471         {
2472           while (text->line_start_cache &&
2473                  text->line_wrap &&
2474                  CACHE_DATA(text->line_start_cache).wraps)
2475             remove_cache_line(text, text->line_start_cache);
2476           
2477           remove_cache_line(text, text->line_start_cache);
2478         }
2479       
2480       last = g_list_last (new);
2481       
2482       last->next = text->line_start_cache;
2483       
2484       if (text->line_start_cache)
2485         text->line_start_cache->prev = last;
2486       
2487       text->line_start_cache = new;
2488     }
2489   else
2490     {
2491       GList *last;
2492       
2493       g_assert (old->prev);
2494       
2495       last = old->prev;
2496       
2497       for (; old_line_count > 0; old_line_count -= 1)
2498         {
2499           while (old && text->line_wrap && CACHE_DATA(old).wraps)
2500             old = remove_cache_line (text, old);
2501           
2502           old = remove_cache_line (text, old);
2503         }
2504       
2505       last->next = new;
2506       new->prev = last;
2507       
2508       last = g_list_last (new);
2509       
2510       last->next = old;
2511       
2512       if (old)
2513         old->prev = last;
2514     }
2515 }
2516
2517 static void
2518 correct_cache_delete (GtkText* text, gint nchars, gint lines)
2519 {
2520   GList* cache = text->current_line;
2521   gint i;
2522   
2523   for (i = 0; cache && i < lines; i += 1, cache = cache->next)
2524     /* nothing */;
2525   
2526   for (; cache; cache = cache->next)
2527     {
2528       GtkPropertyMark *start = &CACHE_DATA(cache).start;
2529       GtkPropertyMark *end = &CACHE_DATA(cache).end;
2530       
2531       start->index -= nchars;
2532       end->index -= nchars;
2533       
2534       if (LAST_INDEX (text, text->point) &&
2535           start->index == text->point.index)
2536         *start = text->point;
2537       else if (start->property == text->point.property)
2538         start->offset = start->index - (text->point.index - text->point.offset);
2539       
2540       if (LAST_INDEX (text, text->point) &&
2541           end->index == text->point.index)
2542         *end = text->point;
2543       if (end->property == text->point.property)
2544         end->offset = end->index - (text->point.index - text->point.offset);
2545       
2546       /*TEXT_ASSERT_MARK(text, start, "start");*/
2547       /*TEXT_ASSERT_MARK(text, end, "end");*/
2548     }
2549 }
2550
2551 static void
2552 delete_expose (GtkText* text, guint nchars, guint old_lines, guint old_pixels)
2553 {
2554   GtkWidget *widget = GTK_WIDGET (text);
2555   
2556   gint pixel_height;
2557   guint new_pixels = 0;
2558   GdkRectangle rect;
2559   GList* new_line = NULL;
2560   gint width, height;
2561   
2562   text->cursor_virtual_x = 0;
2563   
2564   correct_cache_delete (text, nchars, old_lines);
2565   
2566   pixel_height = pixel_height_of(text, text->current_line) -
2567     LINE_HEIGHT(CACHE_DATA(text->current_line));
2568   
2569   if (CACHE_DATA(text->current_line).start.index == text->point.index)
2570     CACHE_DATA(text->current_line).start = text->point;
2571   
2572   new_line = fetch_lines (text,
2573                           &CACHE_DATA(text->current_line).start,
2574                           &CACHE_DATA(text->current_line).tab_cont,
2575                           FetchLinesCount,
2576                           1);
2577   
2578   swap_lines (text, text->current_line, new_line, old_lines);
2579   
2580   text->current_line = new_line;
2581   
2582   new_pixels = total_line_height (text, new_line, 1);
2583   
2584   gdk_window_get_size (text->text_area, &width, &height);
2585   
2586   if (old_pixels != new_pixels)
2587     {
2588       if (!widget->style->bg_pixmap[GTK_STATE_NORMAL])
2589         {
2590           gdk_draw_pixmap (text->text_area,
2591                            text->gc,
2592                            text->text_area,
2593                            0,
2594                            pixel_height + old_pixels,
2595                            0,
2596                            pixel_height + new_pixels,
2597                            width,
2598                            height);
2599         }
2600       text->vadj->upper += new_pixels;
2601       text->vadj->upper -= old_pixels;
2602       adjust_adj (text, text->vadj);
2603     }
2604   
2605   rect.x = 0;
2606   rect.y = pixel_height;
2607   rect.width = width;
2608   rect.height = new_pixels;
2609   
2610   expose_text (text, &rect, FALSE);
2611   gtk_text_draw_focus ( (GtkWidget *) text);
2612   
2613   text->cursor_mark = text->point;
2614   
2615   find_cursor (text, TRUE);
2616   
2617   if (old_pixels != new_pixels)
2618     {
2619       if (widget->style->bg_pixmap[GTK_STATE_NORMAL])
2620         {
2621           rect.x = 0;
2622           rect.y = pixel_height + new_pixels;
2623           rect.width = width;
2624           rect.height = height - rect.y;
2625           
2626           expose_text (text, &rect, FALSE);
2627         }
2628       else
2629         process_exposes (text);
2630     }
2631   
2632   TEXT_ASSERT (text);
2633   TEXT_SHOW(text);
2634 }
2635
2636 /* note, the point has already been moved forward */
2637 static void
2638 correct_cache_insert (GtkText* text, gint nchars)
2639 {
2640   GList *cache;
2641   GtkPropertyMark *start;
2642   GtkPropertyMark *end;
2643   gboolean was_split = FALSE;
2644   
2645   /* We need to distinguish whether the property was split in the
2646    * insert or not, so we check if the point (which points after
2647    * the insertion here), points to the same character as the
2648    * point before. Ugh.
2649    */
2650   if (nchars > 0)
2651     {
2652       GtkPropertyMark tmp_mark = text->point;
2653       move_mark_n (&tmp_mark, -1);
2654       
2655       if (tmp_mark.property != text->point.property)
2656         was_split = TRUE;
2657     }
2658   
2659   /* If we inserted a property exactly at the beginning of the
2660    * line, we have to correct here, or fetch_lines will
2661    * fetch junk.
2662    */
2663   start = &CACHE_DATA(text->current_line).start;
2664
2665   /* Check if if we split exactly at the beginning of the line:
2666    * (was_split won't be set if we are inserting at the end of the text, 
2667    *  so we don't check)
2668    */
2669   if (start->offset ==  MARK_CURRENT_PROPERTY (start)->length)
2670     SET_PROPERTY_MARK (start, start->property->next, 0);
2671   /* Check if we inserted a property at the beginning of the text: */
2672   else if (was_split &&
2673            (start->property == text->point.property) &&
2674            (start->index == text->point.index - nchars))
2675     SET_PROPERTY_MARK (start, start->property->prev, 0);
2676
2677   /* Now correct the offsets, and check for start or end marks that
2678    * are after the point, yet point to a property before the point's
2679    * property. This indicates that they are meant to point to the
2680    * second half of a property we split in insert_text_property(), so
2681    * we fix them up that way.  
2682    */
2683   cache = text->current_line->next;
2684   
2685   for (; cache; cache = cache->next)
2686     {
2687       start = &CACHE_DATA(cache).start;
2688       end = &CACHE_DATA(cache).end;
2689       
2690       if (LAST_INDEX (text, text->point) &&
2691           start->index == text->point.index)
2692         *start = text->point;
2693       else if (start->index >= text->point.index - nchars)
2694         {
2695           if (!was_split && start->property == text->point.property)
2696             move_mark_n(start, nchars);
2697           else
2698             {
2699               if (start->property->next &&
2700                   (start->property->next->next == text->point.property))
2701                 {
2702                   g_assert (start->offset >=  MARK_CURRENT_PROPERTY (start)->length);
2703                   start->offset -= MARK_CURRENT_PROPERTY (start)->length;
2704                   start->property = text->point.property;
2705                 }
2706               start->index += nchars;
2707             }
2708         }
2709       
2710       if (LAST_INDEX (text, text->point) &&
2711           end->index == text->point.index)
2712         *end = text->point;
2713       if (end->index >= text->point.index - nchars)
2714         {
2715           if (!was_split && end->property == text->point.property)
2716             move_mark_n(end, nchars);
2717           else 
2718             {
2719               if (end->property->next &&
2720                   (end->property->next->next == text->point.property))
2721                 {
2722                   g_assert (end->offset >=  MARK_CURRENT_PROPERTY (end)->length);
2723                   end->offset -= MARK_CURRENT_PROPERTY (end)->length;
2724                   end->property = text->point.property;
2725                 }
2726               end->index += nchars;
2727             }
2728         }
2729       
2730       /*TEXT_ASSERT_MARK(text, start, "start");*/
2731       /*TEXT_ASSERT_MARK(text, end, "end");*/
2732     }
2733 }
2734
2735
2736 static void
2737 insert_expose (GtkText* text, guint old_pixels, gint nchars,
2738                guint new_line_count)
2739 {
2740   GtkWidget *widget = GTK_WIDGET (text);
2741   
2742   gint pixel_height;
2743   guint new_pixels = 0;
2744   GdkRectangle rect;
2745   GList* new_lines = NULL;
2746   gint width, height;
2747   
2748   text->cursor_virtual_x = 0;
2749   
2750   undraw_cursor (text, FALSE);
2751   
2752   correct_cache_insert (text, nchars);
2753   
2754   TEXT_SHOW_ADJ (text, text->vadj, "vadj");
2755   
2756   pixel_height = pixel_height_of(text, text->current_line) -
2757     LINE_HEIGHT(CACHE_DATA(text->current_line));
2758   
2759   new_lines = fetch_lines (text,
2760                            &CACHE_DATA(text->current_line).start,
2761                            &CACHE_DATA(text->current_line).tab_cont,
2762                            FetchLinesCount,
2763                            new_line_count);
2764   
2765   swap_lines (text, text->current_line, new_lines, 1);
2766   
2767   text->current_line = new_lines;
2768   
2769   new_pixels = total_line_height (text, new_lines, new_line_count);
2770   
2771   gdk_window_get_size (text->text_area, &width, &height);
2772   
2773   if (old_pixels != new_pixels)
2774     {
2775       if (!widget->style->bg_pixmap[GTK_STATE_NORMAL])
2776         {
2777           gdk_draw_pixmap (text->text_area,
2778                            text->gc,
2779                            text->text_area,
2780                            0,
2781                            pixel_height + old_pixels,
2782                            0,
2783                            pixel_height + new_pixels,
2784                            width,
2785                            height + (old_pixels - new_pixels) - pixel_height);
2786           
2787         }
2788       text->vadj->upper += new_pixels;
2789       text->vadj->upper -= old_pixels;
2790       adjust_adj (text, text->vadj);
2791     }
2792   
2793   rect.x = 0;
2794   rect.y = pixel_height;
2795   rect.width = width;
2796   rect.height = new_pixels;
2797   
2798   expose_text (text, &rect, FALSE);
2799   gtk_text_draw_focus ( (GtkWidget *) text);
2800   
2801   text->cursor_mark = text->point;
2802   
2803   find_cursor (text, TRUE);
2804   
2805   draw_cursor (text, FALSE);
2806   
2807   if (old_pixels != new_pixels)
2808     {
2809       if (widget->style->bg_pixmap[GTK_STATE_NORMAL])
2810         {
2811           rect.x = 0;
2812           rect.y = pixel_height + new_pixels;
2813           rect.width = width;
2814           rect.height = height - rect.y;
2815           
2816           expose_text (text, &rect, FALSE);
2817         }
2818       else
2819         process_exposes (text);
2820     }
2821   
2822   TEXT_SHOW_ADJ (text, text->vadj, "vadj");
2823   TEXT_ASSERT (text);
2824   TEXT_SHOW(text);
2825 }
2826
2827 /* Text property functions */
2828
2829 static guint
2830 font_hash (gconstpointer font)
2831 {
2832   return gdk_font_id ((const GdkFont*) font);
2833 }
2834
2835 static GHashTable *font_cache_table = NULL;
2836
2837 static GtkTextFont*
2838 get_text_font (GdkFont* gfont)
2839 {
2840   GtkTextFont* tf;
2841   gint i;
2842   
2843   if (!font_cache_table)
2844     font_cache_table = g_hash_table_new (font_hash, (GEqualFunc) gdk_font_equal);
2845   
2846   tf = g_hash_table_lookup (font_cache_table, gfont);
2847   
2848   if (tf)
2849     {
2850       tf->ref_count++;
2851       return tf;
2852     }
2853
2854   tf = g_new (GtkTextFont, 1);
2855   tf->ref_count = 1;
2856
2857   tf->gdk_font = gfont;
2858   gdk_font_ref (gfont);
2859   
2860   for(i = 0; i < 256; i += 1)
2861     tf->char_widths[i] = gdk_char_width (gfont, (char)i);
2862   
2863   g_hash_table_insert (font_cache_table, gfont, tf);
2864   
2865   return tf;
2866 }
2867
2868 static void
2869 text_font_unref (GtkTextFont *text_font)
2870 {
2871   text_font->ref_count--;
2872   if (text_font->ref_count == 0)
2873     {
2874       g_hash_table_remove (font_cache_table, text_font->gdk_font);
2875       gdk_font_unref (text_font->gdk_font);
2876       g_free (text_font);
2877     }
2878 }
2879
2880 static gint
2881 text_properties_equal (TextProperty* prop, GdkFont* font, const GdkColor *fore, const GdkColor *back)
2882 {
2883   if (prop->flags & PROPERTY_FONT)
2884     {
2885       gboolean retval;
2886       GtkTextFont *text_font;
2887
2888       if (!font)
2889         return FALSE;
2890
2891       text_font = get_text_font (font);
2892
2893       retval = (prop->font == text_font);
2894       text_font_unref (text_font);
2895       
2896       if (!retval)
2897         return FALSE;
2898     }
2899   else
2900     if (font != NULL)
2901       return FALSE;
2902
2903   if (prop->flags & PROPERTY_FOREGROUND)
2904     {
2905       if (!fore || !gdk_color_equal (&prop->fore_color, fore))
2906         return FALSE;
2907     }
2908   else
2909     if (fore != NULL)
2910       return FALSE;
2911
2912   if (prop->flags & PROPERTY_BACKGROUND)
2913     {
2914       if (!back || !gdk_color_equal (&prop->back_color, back))
2915         return FALSE;
2916     }
2917   else
2918     if (back != NULL)
2919       return FALSE;
2920   
2921   return TRUE;
2922 }
2923
2924 static void
2925 realize_property (GtkText *text, TextProperty *prop)
2926 {
2927   GdkColormap *colormap = gtk_widget_get_colormap (GTK_WIDGET (text));
2928
2929   if (prop->flags & PROPERTY_FOREGROUND)
2930     gdk_colormap_alloc_color (colormap, &prop->fore_color, FALSE, FALSE);
2931   
2932   if (prop->flags & PROPERTY_BACKGROUND)
2933     gdk_colormap_alloc_color (colormap, &prop->back_color, FALSE, FALSE);
2934 }
2935
2936 static void
2937 realize_properties (GtkText *text)
2938 {
2939   GList *tmp_list = text->text_properties;
2940
2941   while (tmp_list)
2942     {
2943       realize_property (text, tmp_list->data);
2944       
2945       tmp_list = tmp_list->next;
2946     }
2947 }
2948
2949 static void
2950 unrealize_property (GtkText *text, TextProperty *prop)
2951 {
2952   GdkColormap *colormap = gtk_widget_get_colormap (GTK_WIDGET (text));
2953
2954   if (prop->flags & PROPERTY_FOREGROUND)
2955     gdk_colormap_free_colors (colormap, &prop->fore_color, 1);
2956   
2957   if (prop->flags & PROPERTY_BACKGROUND)
2958     gdk_colormap_free_colors (colormap, &prop->back_color, 1);
2959 }
2960
2961 static void
2962 unrealize_properties (GtkText *text)
2963 {
2964   GList *tmp_list = text->text_properties;
2965
2966   while (tmp_list)
2967     {
2968       unrealize_property (text, tmp_list->data);
2969
2970       tmp_list = tmp_list->next;
2971     }
2972 }
2973
2974 static TextProperty*
2975 new_text_property (GtkText *text, GdkFont *font, const GdkColor* fore,
2976                    const GdkColor* back, guint length)
2977 {
2978   TextProperty *prop;
2979   
2980   if (text_property_chunk == NULL)
2981     {
2982       text_property_chunk = g_mem_chunk_new ("text property mem chunk",
2983                                              sizeof(TextProperty),
2984                                              1024*sizeof(TextProperty),
2985                                              G_ALLOC_AND_FREE);
2986     }
2987   
2988   prop = g_chunk_new(TextProperty, text_property_chunk);
2989
2990   prop->flags = 0;
2991   if (font)
2992     {
2993       prop->flags |= PROPERTY_FONT;
2994       prop->font = get_text_font (font);
2995     }
2996   else
2997     prop->font = NULL;
2998   
2999   if (fore)
3000     {
3001       prop->flags |= PROPERTY_FOREGROUND;
3002       prop->fore_color = *fore;
3003     }
3004       
3005   if (back)
3006     {
3007       prop->flags |= PROPERTY_BACKGROUND;
3008       prop->back_color = *back;
3009     }
3010
3011   prop->length = length;
3012
3013   if (GTK_WIDGET_REALIZED (text))
3014     realize_property (text, prop);
3015
3016   return prop;
3017 }
3018
3019 static void
3020 destroy_text_property (TextProperty *prop)
3021 {
3022   if (prop->font)
3023     text_font_unref (prop->font);
3024   
3025   g_mem_chunk_free (text_property_chunk, prop);
3026 }
3027
3028 /* Flop the memory between the point and the gap around like a
3029  * dead fish. */
3030 static void
3031 move_gap (GtkText* text, guint index)
3032 {
3033   if (text->gap_position < index)
3034     {
3035       gint diff = index - text->gap_position;
3036       
3037       if (text->use_wchar)
3038         g_memmove (text->text.wc + text->gap_position,
3039                    text->text.wc + text->gap_position + text->gap_size,
3040                    diff*sizeof (GdkWChar));
3041       else
3042         g_memmove (text->text.ch + text->gap_position,
3043                    text->text.ch + text->gap_position + text->gap_size,
3044                    diff);
3045       
3046       text->gap_position = index;
3047     }
3048   else if (text->gap_position > index)
3049     {
3050       gint diff = text->gap_position - index;
3051       
3052       if (text->use_wchar)
3053         g_memmove (text->text.wc + index + text->gap_size,
3054                    text->text.wc + index,
3055                    diff*sizeof (GdkWChar));
3056       else
3057         g_memmove (text->text.ch + index + text->gap_size,
3058                    text->text.ch + index,
3059                    diff);
3060       
3061       text->gap_position = index;
3062     }
3063 }
3064
3065 /* Increase the gap size. */
3066 static void
3067 make_forward_space (GtkText* text, guint len)
3068 {
3069   if (text->gap_size < len)
3070     {
3071       guint sum = MAX(2*len, MIN_GAP_SIZE) + text->text_end;
3072       
3073       if (sum >= text->text_len)
3074         {
3075           guint i = 1;
3076           
3077           while (i <= sum) i <<= 1;
3078           
3079           if (text->use_wchar)
3080             text->text.wc = (GdkWChar *)g_realloc(text->text.wc,
3081                                                   i*sizeof(GdkWChar));
3082           else
3083             text->text.ch = (guchar *)g_realloc(text->text.ch, i);
3084           text->text_len = i;
3085         }
3086       
3087       if (text->use_wchar)
3088         g_memmove (text->text.wc + text->gap_position + text->gap_size + 2*len,
3089                    text->text.wc + text->gap_position + text->gap_size,
3090                    (text->text_end - (text->gap_position + text->gap_size))
3091                    *sizeof(GdkWChar));
3092       else
3093         g_memmove (text->text.ch + text->gap_position + text->gap_size + 2*len,
3094                    text->text.ch + text->gap_position + text->gap_size,
3095                    text->text_end - (text->gap_position + text->gap_size));
3096       
3097       text->text_end += len*2;
3098       text->gap_size += len*2;
3099     }
3100 }
3101
3102 /* Inserts into the text property list a list element that guarantees
3103  * that for len characters following the point, text has the correct
3104  * property.  does not move point.  adjusts text_properties_point and
3105  * text_properties_point_offset relative to the current value of
3106  * point. */
3107 static void
3108 insert_text_property (GtkText* text, GdkFont* font,
3109                       const GdkColor *fore, const GdkColor* back, guint len)
3110 {
3111   GtkPropertyMark *mark = &text->point;
3112   TextProperty* forward_prop = MARK_CURRENT_PROPERTY(mark);
3113   TextProperty* backward_prop = MARK_PREV_PROPERTY(mark);
3114   
3115   if (MARK_OFFSET(mark) == 0)
3116     {
3117       /* Point is on the boundary of two properties.
3118        * If it is the same as either, grow, else insert
3119        * a new one. */
3120       
3121       if (text_properties_equal(forward_prop, font, fore, back))
3122         {
3123           /* Grow the property in front of us. */
3124           
3125           MARK_PROPERTY_LENGTH(mark) += len;
3126         }
3127       else if (backward_prop &&
3128                text_properties_equal(backward_prop, font, fore, back))
3129         {
3130           /* Grow property behind us, point property and offset
3131            * change. */
3132           
3133           SET_PROPERTY_MARK (&text->point,
3134                              MARK_PREV_LIST_PTR (mark),
3135                              backward_prop->length);
3136           
3137           backward_prop->length += len;
3138         }
3139       else if ((MARK_NEXT_LIST_PTR(mark) == NULL) &&
3140                (forward_prop->length == 1))
3141         {
3142           /* Next property just has last position, take it over */
3143
3144           if (GTK_WIDGET_REALIZED (text))
3145             unrealize_property (text, forward_prop);
3146
3147           forward_prop->flags = 0;
3148           if (font)
3149             {
3150               forward_prop->flags |= PROPERTY_FONT;
3151               forward_prop->font = get_text_font (font);
3152             }
3153           else
3154             forward_prop->font = NULL;
3155             
3156           if (fore)
3157             {
3158               forward_prop->flags |= PROPERTY_FOREGROUND;
3159               forward_prop->fore_color = *fore;
3160             }
3161           if (back)
3162             {
3163               forward_prop->flags |= PROPERTY_BACKGROUND;
3164               forward_prop->back_color = *back;
3165             }
3166           forward_prop->length += len;
3167
3168           if (GTK_WIDGET_REALIZED (text))
3169             realize_property (text, forward_prop);
3170         }
3171       else
3172         {
3173           /* Splice a new property into the list. */
3174           
3175           GList* new_prop = g_list_alloc();
3176           
3177           new_prop->next = MARK_LIST_PTR(mark);
3178           new_prop->prev = MARK_PREV_LIST_PTR(mark);
3179           new_prop->next->prev = new_prop;
3180           
3181           if (new_prop->prev)
3182             new_prop->prev->next = new_prop;
3183
3184           new_prop->data = new_text_property (text, font, fore, back, len);
3185
3186           SET_PROPERTY_MARK (mark, new_prop, 0);
3187         }
3188     }
3189   else
3190     {
3191       /* The following will screw up the line_start cache,
3192        * we'll fix it up in correct_cache_insert
3193        */
3194       
3195       /* In the middle of forward_prop, if properties are equal,
3196        * just add to its length, else split it into two and splice
3197        * in a new one. */
3198       if (text_properties_equal (forward_prop, font, fore, back))
3199         {
3200           forward_prop->length += len;
3201         }
3202       else if ((MARK_NEXT_LIST_PTR(mark) == NULL) &&
3203                (MARK_OFFSET(mark) + 1 == forward_prop->length))
3204         {
3205           /* Inserting before only the last position in the text */
3206           
3207           GList* new_prop;
3208           forward_prop->length -= 1;
3209           
3210           new_prop = g_list_alloc();
3211           new_prop->data = new_text_property (text, font, fore, back, len+1);
3212           new_prop->prev = MARK_LIST_PTR(mark);
3213           new_prop->next = NULL;
3214           MARK_NEXT_LIST_PTR(mark) = new_prop;
3215           
3216           SET_PROPERTY_MARK (mark, new_prop, 0);
3217         }
3218       else
3219         {
3220           GList* new_prop = g_list_alloc();
3221           GList* new_prop_forward = g_list_alloc();
3222           gint old_length = forward_prop->length;
3223           GList* next = MARK_NEXT_LIST_PTR(mark);
3224           
3225           /* Set the new lengths according to where they are split.  Construct
3226            * two new properties. */
3227           forward_prop->length = MARK_OFFSET(mark);
3228
3229           new_prop_forward->data = 
3230             new_text_property(text,
3231                               forward_prop->flags & PROPERTY_FONT ? 
3232                                      forward_prop->font->gdk_font : NULL,
3233                               forward_prop->flags & PROPERTY_FOREGROUND ? 
3234                                      &forward_prop->fore_color : NULL,
3235                               forward_prop->flags & PROPERTY_BACKGROUND ? 
3236                                      &forward_prop->back_color : NULL,
3237                               old_length - forward_prop->length);
3238
3239           new_prop->data = new_text_property(text, font, fore, back, len);
3240
3241           /* Now splice things in. */
3242           MARK_NEXT_LIST_PTR(mark) = new_prop;
3243           new_prop->prev = MARK_LIST_PTR(mark);
3244           
3245           new_prop->next = new_prop_forward;
3246           new_prop_forward->prev = new_prop;
3247           
3248           new_prop_forward->next = next;
3249           
3250           if (next)
3251             next->prev = new_prop_forward;
3252           
3253           SET_PROPERTY_MARK (mark, new_prop, 0);
3254         }
3255     }
3256   
3257   while (text->text_properties_end->next)
3258     text->text_properties_end = text->text_properties_end->next;
3259   
3260   while (text->text_properties->prev)
3261     text->text_properties = text->text_properties->prev;
3262 }
3263
3264 static void
3265 delete_text_property (GtkText* text, guint nchars)
3266 {
3267   /* Delete nchars forward from point. */
3268   
3269   /* Deleting text properties is problematical, because we
3270    * might be storing around marks pointing to a property.
3271    *
3272    * The marks in question and how we handle them are:
3273    *
3274    *  point: We know the new value, since it will be at the
3275    *         end of the deleted text, and we move it there
3276    *         first.
3277    *  cursor: We just remove the mark and set it equal to the
3278    *         point after the operation.
3279    *  line-start cache: We replace most affected lines.
3280    *         The current line gets used to fetch the new
3281    *         lines so, if necessary, (delete at the beginning
3282    *         of a line) we fix it up by setting it equal to the
3283    *         point.
3284    */
3285   
3286   TextProperty *prop;
3287   GList        *tmp;
3288   gint          is_first;
3289   
3290   for(; nchars; nchars -= 1)
3291     {
3292       prop = MARK_CURRENT_PROPERTY(&text->point);
3293       
3294       prop->length -= 1;
3295       
3296       if (prop->length == 0)
3297         {
3298           tmp = MARK_LIST_PTR (&text->point);
3299           
3300           is_first = tmp == text->text_properties;
3301           
3302           MARK_LIST_PTR (&text->point) = g_list_remove_link (tmp, tmp);
3303           text->point.offset = 0;
3304
3305           if (GTK_WIDGET_REALIZED (text))
3306             unrealize_property (text, prop);
3307
3308           destroy_text_property (prop);
3309           g_list_free_1 (tmp);
3310           
3311           prop = MARK_CURRENT_PROPERTY (&text->point);
3312           
3313           if (is_first)
3314             text->text_properties = MARK_LIST_PTR (&text->point);
3315           
3316           g_assert (prop->length != 0);
3317         }
3318       else if (prop->length == text->point.offset)
3319         {
3320           MARK_LIST_PTR (&text->point) = MARK_NEXT_LIST_PTR (&text->point);
3321           text->point.offset = 0;
3322         }
3323     }
3324   
3325   /* Check to see if we have just the single final position remaining
3326    * along in a property; if so, combine it with the previous property
3327    */
3328   if (LAST_INDEX (text, text->point) && 
3329       (MARK_OFFSET (&text->point) == 0) &&
3330       (MARK_PREV_LIST_PTR(&text->point) != NULL))
3331     {
3332       tmp = MARK_LIST_PTR (&text->point);
3333       prop = MARK_CURRENT_PROPERTY(&text->point);
3334       
3335       MARK_LIST_PTR (&text->point) = MARK_PREV_LIST_PTR (&text->point);
3336       MARK_CURRENT_PROPERTY(&text->point)->length += 1;
3337       MARK_NEXT_LIST_PTR(&text->point) = NULL;
3338       
3339       text->point.offset = MARK_CURRENT_PROPERTY(&text->point)->length - 1;
3340       
3341       if (GTK_WIDGET_REALIZED (text))
3342         unrealize_property (text, prop);
3343
3344       destroy_text_property (prop);
3345       g_list_free_1 (tmp);
3346     }
3347 }
3348
3349 static void
3350 init_properties (GtkText *text)
3351 {
3352   if (!text->text_properties)
3353     {
3354       text->text_properties = g_list_alloc();
3355       text->text_properties->next = NULL;
3356       text->text_properties->prev = NULL;
3357       text->text_properties->data = new_text_property (text, NULL, NULL, NULL, 1);
3358       text->text_properties_end = text->text_properties;
3359       
3360       SET_PROPERTY_MARK (&text->point, text->text_properties, 0);
3361       
3362       text->point.index = 0;
3363     }
3364 }
3365
3366
3367 /**********************************************************************/
3368 /*                         Property Movement                          */
3369 /**********************************************************************/
3370
3371 static void
3372 move_mark_n (GtkPropertyMark* mark, gint n)
3373 {
3374   if (n > 0)
3375     advance_mark_n(mark, n);
3376   else if (n < 0)
3377     decrement_mark_n(mark, -n);
3378 }
3379
3380 static void
3381 advance_mark (GtkPropertyMark* mark)
3382 {
3383   TextProperty* prop = MARK_CURRENT_PROPERTY (mark);
3384   
3385   mark->index += 1;
3386   
3387   if (prop->length > mark->offset + 1)
3388     mark->offset += 1;
3389   else
3390     {
3391       mark->property = MARK_NEXT_LIST_PTR (mark);
3392       mark->offset   = 0;
3393     }
3394 }
3395
3396 static void
3397 advance_mark_n (GtkPropertyMark* mark, gint n)
3398 {
3399   gint i;
3400   TextProperty* prop;
3401
3402   g_assert (n > 0);
3403
3404   i = 0;                        /* otherwise it migth not be init. */
3405   prop = MARK_CURRENT_PROPERTY(mark);
3406
3407   if ((prop->length - mark->offset - 1) < n) { /* if we need to change prop. */
3408     /* to make it easier */
3409     n += (mark->offset);
3410     mark->index -= mark->offset;
3411     mark->offset = 0;
3412     /* first we take seven-mile-leaps to get to the right text
3413      * property. */
3414     while ((n-i) > prop->length - 1) {
3415       i += prop->length;
3416       mark->index += prop->length;
3417       mark->property = MARK_NEXT_LIST_PTR (mark);
3418       prop = MARK_CURRENT_PROPERTY (mark);
3419     }
3420   }
3421
3422   /* and then the rest */
3423   mark->index += n - i;
3424   mark->offset += n - i;
3425 }
3426
3427 static void
3428 decrement_mark (GtkPropertyMark* mark)
3429 {
3430   mark->index -= 1;
3431   
3432   if (mark->offset > 0)
3433     mark->offset -= 1;
3434   else
3435     {
3436       mark->property = MARK_PREV_LIST_PTR (mark);
3437       mark->offset   = MARK_CURRENT_PROPERTY (mark)->length - 1;
3438     }
3439 }
3440
3441 static void
3442 decrement_mark_n (GtkPropertyMark* mark, gint n)
3443 {
3444   g_assert (n > 0);
3445
3446   while (mark->offset < n) {
3447     /* jump to end of prev */
3448     n -= mark->offset + 1;
3449     mark->index -= mark->offset + 1;
3450     mark->property = MARK_PREV_LIST_PTR (mark);
3451     mark->offset = MARK_CURRENT_PROPERTY (mark)->length - 1;
3452   }
3453
3454   /* and the rest */
3455   mark->index -= n;
3456   mark->offset -= n;
3457 }
3458  
3459 static GtkPropertyMark
3460 find_mark (GtkText* text, guint mark_position)
3461 {
3462   return find_mark_near (text, mark_position, &text->point);
3463 }
3464
3465 /*
3466  * You can also start from the end, what a drag.
3467  */
3468 static GtkPropertyMark
3469 find_mark_near (GtkText* text, guint mark_position, const GtkPropertyMark* near)
3470 {
3471   gint diffa;
3472   gint diffb;
3473   
3474   GtkPropertyMark mark;
3475   
3476   if (!near)
3477     diffa = mark_position + 1;
3478   else
3479     diffa = mark_position - near->index;
3480   
3481   diffb = mark_position;
3482   
3483   if (diffa < 0)
3484     diffa = -diffa;
3485   
3486   if (diffa <= diffb)
3487     {
3488       mark = *near;
3489     }
3490   else
3491     {
3492       mark.index = 0;
3493       mark.property = text->text_properties;
3494       mark.offset = 0;
3495     }
3496
3497   move_mark_n (&mark, mark_position - mark.index);
3498    
3499   return mark;
3500 }
3501
3502 /* This routine must be called with scroll == FALSE, only when
3503  * point is at least partially on screen
3504  */
3505
3506 static void
3507 find_line_containing_point (GtkText* text, guint point,
3508                             gboolean scroll)
3509 {
3510   GList* cache;
3511   gint height;
3512   
3513   text->current_line = NULL;
3514
3515   TEXT_SHOW (text);
3516
3517   /* Scroll backwards until the point is on screen
3518    */
3519   while (CACHE_DATA(text->line_start_cache).start.index > point)
3520     scroll_int (text, - LINE_HEIGHT(CACHE_DATA(text->line_start_cache)));
3521
3522   /* Now additionally try to make sure that the point is fully on screen
3523    */
3524   if (scroll)
3525     {
3526       while (text->first_cut_pixels != 0 && 
3527              text->line_start_cache->next &&
3528              CACHE_DATA(text->line_start_cache->next).start.index > point)
3529         scroll_int (text, - LINE_HEIGHT(CACHE_DATA(text->line_start_cache->next)));
3530     }
3531
3532   gdk_window_get_size (text->text_area, NULL, &height);
3533   
3534   for (cache = text->line_start_cache; cache; cache = cache->next)
3535     {
3536       guint lph;
3537       
3538       if (CACHE_DATA(cache).end.index >= point ||
3539           LAST_INDEX(text, CACHE_DATA(cache).end))
3540         {
3541           text->current_line = cache; /* LOOK HERE, this proc has an
3542                                        * important side effect. */
3543           return;
3544         }
3545       
3546       TEXT_SHOW_LINE (text, cache, "cache");
3547       
3548       if (cache->next == NULL)
3549         fetch_lines_forward (text, 1);
3550       
3551       if (scroll)
3552         {
3553           lph = pixel_height_of (text, cache->next);
3554           
3555           /* Scroll the bottom of the line is on screen, or until
3556            * the line is the first onscreen line.
3557            */
3558           while (cache->next != text->line_start_cache && lph > height)
3559             {
3560               TEXT_SHOW_LINE (text, cache, "cache");
3561               TEXT_SHOW_LINE (text, cache->next, "cache->next");
3562               scroll_int (text, LINE_HEIGHT(CACHE_DATA(cache->next)));
3563               lph = pixel_height_of (text, cache->next);
3564             }
3565         }
3566     }
3567   
3568   g_assert_not_reached (); /* Must set text->current_line here */
3569 }
3570
3571 static guint
3572 pixel_height_of (GtkText* text, GList* cache_line)
3573 {
3574   gint pixels = - text->first_cut_pixels;
3575   GList *cache = text->line_start_cache;
3576   
3577   while (TRUE) {
3578     pixels += LINE_HEIGHT (CACHE_DATA(cache));
3579     
3580     if (cache->data == cache_line->data)
3581       break;
3582     
3583     cache = cache->next;
3584   }
3585   
3586   return pixels;
3587 }
3588
3589 /**********************************************************************/
3590 /*                      Search and Placement                          */
3591 /**********************************************************************/
3592
3593 static gint
3594 find_char_width (GtkText* text, const GtkPropertyMark *mark, const TabStopMark *tab_mark)
3595 {
3596   GdkWChar ch;
3597   gint16* char_widths;
3598   
3599   if (LAST_INDEX (text, *mark))
3600     return 0;
3601   
3602   ch = GTK_TEXT_INDEX (text, mark->index);
3603   char_widths = MARK_CURRENT_TEXT_FONT (text, mark)->char_widths;
3604
3605   if (ch == '\t')
3606     {
3607       return tab_mark->to_next_tab * char_widths[' '];
3608     }
3609   else if (ch < 256)
3610     {
3611       return char_widths[ch];
3612     }
3613   else
3614     {
3615       return gdk_char_width_wc(MARK_CURRENT_TEXT_FONT(text, mark)->gdk_font, ch);
3616     }
3617 }
3618
3619 static void
3620 advance_tab_mark (GtkText* text, TabStopMark* tab_mark, GdkWChar ch)
3621 {
3622   if (tab_mark->to_next_tab == 1 || ch == '\t')
3623     {
3624       if (tab_mark->tab_stops->next)
3625         {
3626           tab_mark->tab_stops = tab_mark->tab_stops->next;
3627           tab_mark->to_next_tab = (gulong) tab_mark->tab_stops->data;
3628         }
3629       else
3630         {
3631           tab_mark->to_next_tab = text->default_tab_width;
3632         }
3633     }
3634   else
3635     {
3636       tab_mark->to_next_tab -= 1;
3637     }
3638 }
3639
3640 static void
3641 advance_tab_mark_n (GtkText* text, TabStopMark* tab_mark, gint n)
3642      /* No tabs! */
3643 {
3644   while (n--)
3645     advance_tab_mark (text, tab_mark, 0);
3646 }
3647
3648 static void
3649 find_cursor_at_line (GtkText* text, const LineParams* start_line, gint pixel_height)
3650 {
3651   GdkWChar ch;
3652   
3653   GtkPropertyMark mark        = start_line->start;
3654   TabStopMark  tab_mark    = start_line->tab_cont.tab_start;
3655   gint         pixel_width = LINE_START_PIXEL (*start_line);
3656   
3657   while (mark.index < text->cursor_mark.index)
3658     {
3659       pixel_width += find_char_width (text, &mark, &tab_mark);
3660       
3661       advance_tab_mark (text, &tab_mark, GTK_TEXT_INDEX(text, mark.index));
3662       advance_mark (&mark);
3663     }
3664   
3665   text->cursor_pos_x       = pixel_width;
3666   text->cursor_pos_y       = pixel_height;
3667   text->cursor_char_offset = start_line->font_descent;
3668   text->cursor_mark        = mark;
3669   
3670   ch = LAST_INDEX (text, mark) ? 
3671     LINE_DELIM : GTK_TEXT_INDEX (text, mark.index);
3672   
3673   if ((text->use_wchar) ? gdk_iswspace (ch) : isspace (ch))
3674     text->cursor_char = 0;
3675   else
3676     text->cursor_char = ch;
3677 }
3678
3679 static void
3680 find_cursor (GtkText* text, gboolean scroll)
3681 {
3682   if (GTK_WIDGET_REALIZED (text))
3683     {
3684       find_line_containing_point (text, text->cursor_mark.index, scroll);
3685       
3686       if (text->current_line)
3687         find_cursor_at_line (text,
3688                              &CACHE_DATA(text->current_line),
3689                              pixel_height_of(text, text->current_line));
3690     }
3691   
3692   GTK_OLD_EDITABLE (text)->current_pos = text->cursor_mark.index;
3693 }
3694
3695 static void
3696 find_mouse_cursor_at_line (GtkText *text, const LineParams* lp,
3697                            guint line_pixel_height,
3698                            gint button_x)
3699 {
3700   GtkPropertyMark mark     = lp->start;
3701   TabStopMark  tab_mark = lp->tab_cont.tab_start;
3702   
3703   gint char_width = find_char_width(text, &mark, &tab_mark);
3704   gint pixel_width = LINE_START_PIXEL (*lp) + (char_width+1)/2;
3705   
3706   text->cursor_pos_y = line_pixel_height;
3707   
3708   for (;;)
3709     {
3710       GdkWChar ch = LAST_INDEX (text, mark) ? 
3711         LINE_DELIM : GTK_TEXT_INDEX (text, mark.index);
3712       
3713       if (button_x < pixel_width || mark.index == lp->end.index)
3714         {
3715           text->cursor_pos_x       = pixel_width - (char_width+1)/2;
3716           text->cursor_mark        = mark;
3717           text->cursor_char_offset = lp->font_descent;
3718           
3719           if ((text->use_wchar) ? gdk_iswspace (ch) : isspace (ch))
3720             text->cursor_char = 0;
3721           else
3722             text->cursor_char = ch;
3723           
3724           break;
3725         }
3726       
3727       advance_tab_mark (text, &tab_mark, ch);
3728       advance_mark (&mark);
3729       
3730       pixel_width += char_width/2;
3731       
3732       char_width = find_char_width (text, &mark, &tab_mark);
3733       
3734       pixel_width += (char_width+1)/2;
3735     }
3736 }
3737
3738 static void
3739 find_mouse_cursor (GtkText* text, gint x, gint y)
3740 {
3741   gint pixel_height;
3742   GList* cache = text->line_start_cache;
3743   
3744   g_assert (cache);
3745   
3746   pixel_height = - text->first_cut_pixels;
3747   
3748   for (; cache; cache = cache->next)
3749     {
3750       pixel_height += LINE_HEIGHT(CACHE_DATA(cache));
3751       
3752       if (y < pixel_height || !cache->next)
3753         {
3754           find_mouse_cursor_at_line (text, &CACHE_DATA(cache), pixel_height, x);
3755           
3756           find_cursor (text, FALSE);
3757           
3758           return;
3759         }
3760     }
3761 }
3762
3763 /**********************************************************************/
3764 /*                          Cache Manager                             */
3765 /**********************************************************************/
3766
3767 static void
3768 free_cache (GtkText* text)
3769 {
3770   GList* cache = text->line_start_cache;
3771   
3772   if (cache)
3773     {
3774       while (cache->prev)
3775         cache = cache->prev;
3776       
3777       text->line_start_cache = cache;
3778     }
3779   
3780   for (; cache; cache = cache->next)
3781     g_mem_chunk_free (params_mem_chunk, cache->data);
3782   
3783   g_list_free (text->line_start_cache);
3784   
3785   text->line_start_cache = NULL;
3786 }
3787
3788 static GList*
3789 remove_cache_line (GtkText* text, GList* member)
3790 {
3791   GList *list;
3792   
3793   if (member == NULL)
3794     return NULL;
3795   
3796   if (member == text->line_start_cache)
3797     text->line_start_cache = text->line_start_cache->next;
3798   
3799   if (member->prev)
3800     member->prev->next = member->next;
3801   
3802   if (member->next)
3803     member->next->prev = member->prev;
3804   
3805   list = member->next;
3806   
3807   g_mem_chunk_free (params_mem_chunk, member->data);
3808   g_list_free_1 (member);
3809   
3810   return list;
3811 }
3812
3813 /**********************************************************************/
3814 /*                           Key Motion                               */
3815 /**********************************************************************/
3816
3817 static void
3818 move_cursor_buffer_ver (GtkText *text, int dir)
3819 {
3820   undraw_cursor (text, FALSE);
3821   
3822   if (dir > 0)
3823     {
3824       scroll_int (text, text->vadj->upper);
3825       text->cursor_mark = find_this_line_start_mark (text,
3826                                                      TEXT_LENGTH (text),
3827                                                      &text->cursor_mark);
3828     }
3829   else
3830     {
3831       scroll_int (text, - text->vadj->value);
3832       text->cursor_mark = find_this_line_start_mark (text,
3833                                                      0,
3834                                                      &text->cursor_mark);
3835     }
3836   
3837   find_cursor (text, TRUE);
3838   draw_cursor (text, FALSE);
3839 }
3840
3841 static void
3842 move_cursor_page_ver (GtkText *text, int dir)
3843 {
3844   scroll_int (text, dir * text->vadj->page_increment);
3845 }
3846
3847 static void
3848 move_cursor_ver (GtkText *text, int count)
3849 {
3850   gint i;
3851   GtkPropertyMark mark;
3852   gint offset;
3853   
3854   mark = find_this_line_start_mark (text, text->cursor_mark.index, &text->cursor_mark);
3855   offset = text->cursor_mark.index - mark.index;
3856   
3857   if (offset > text->cursor_virtual_x)
3858     text->cursor_virtual_x = offset;
3859   
3860   if (count < 0)
3861     {
3862       if (mark.index == 0)
3863         return;
3864       
3865       decrement_mark (&mark);
3866       mark = find_this_line_start_mark (text, mark.index, &mark);
3867     }
3868   else
3869     {
3870       mark = text->cursor_mark;
3871       
3872       while (!LAST_INDEX(text, mark) && GTK_TEXT_INDEX(text, mark.index) != LINE_DELIM)
3873         advance_mark (&mark);
3874       
3875       if (LAST_INDEX(text, mark))
3876         return;
3877       
3878       advance_mark (&mark);
3879     }
3880   
3881   for (i=0; i < text->cursor_virtual_x; i += 1, advance_mark(&mark))
3882     if (LAST_INDEX(text, mark) ||
3883         GTK_TEXT_INDEX(text, mark.index) == LINE_DELIM)
3884       break;
3885   
3886   undraw_cursor (text, FALSE);
3887   
3888   text->cursor_mark = mark;
3889   
3890   find_cursor (text, TRUE);
3891   
3892   draw_cursor (text, FALSE);
3893 }
3894
3895 static void
3896 move_cursor_hor (GtkText *text, int count)
3897 {
3898   /* count should be +-1. */
3899   if ( (count > 0 && text->cursor_mark.index + count > TEXT_LENGTH(text)) ||
3900        (count < 0 && text->cursor_mark.index < (- count)) ||
3901        (count == 0) )
3902     return;
3903   
3904   text->cursor_virtual_x = 0;
3905   
3906   undraw_cursor (text, FALSE);
3907   
3908   move_mark_n (&text->cursor_mark, count);
3909   
3910   find_cursor (text, TRUE);
3911   
3912   draw_cursor (text, FALSE);
3913 }
3914
3915 static void 
3916 gtk_text_move_cursor (GtkOldEditable *old_editable,
3917                       gint            x,
3918                       gint            y)
3919 {
3920   if (x > 0)
3921     {
3922       while (x-- != 0)
3923         move_cursor_hor (GTK_TEXT (old_editable), 1);
3924     }
3925   else if (x < 0)
3926     {
3927       while (x++ != 0)
3928         move_cursor_hor (GTK_TEXT (old_editable), -1);
3929     }
3930   
3931   if (y > 0)
3932     {
3933       while (y-- != 0)
3934         move_cursor_ver (GTK_TEXT (old_editable), 1);
3935     }
3936   else if (y < 0)
3937     {
3938       while (y++ != 0)
3939         move_cursor_ver (GTK_TEXT (old_editable), -1);
3940     }
3941 }
3942
3943 static void
3944 gtk_text_move_forward_character (GtkText *text)
3945 {
3946   move_cursor_hor (text, 1);
3947 }
3948
3949 static void
3950 gtk_text_move_backward_character (GtkText *text)
3951 {
3952   move_cursor_hor (text, -1);
3953 }
3954
3955 static void
3956 gtk_text_move_next_line (GtkText *text)
3957 {
3958   move_cursor_ver (text, 1);
3959 }
3960
3961 static void
3962 gtk_text_move_previous_line (GtkText *text)
3963 {
3964   move_cursor_ver (text, -1);
3965 }
3966
3967 static void 
3968 gtk_text_move_word (GtkOldEditable *old_editable,
3969                     gint            n)
3970 {
3971   if (n > 0)
3972     {
3973       while (n-- != 0)
3974         gtk_text_move_forward_word (GTK_TEXT (old_editable));
3975     }
3976   else if (n < 0)
3977     {
3978       while (n++ != 0)
3979         gtk_text_move_backward_word (GTK_TEXT (old_editable));
3980     }
3981 }
3982
3983 static void
3984 gtk_text_move_forward_word (GtkText *text)
3985 {
3986   text->cursor_virtual_x = 0;
3987   
3988   undraw_cursor (text, FALSE);
3989   
3990   if (text->use_wchar)
3991     {
3992       while (!LAST_INDEX (text, text->cursor_mark) && 
3993              !gdk_iswalnum (GTK_TEXT_INDEX(text, text->cursor_mark.index)))
3994         advance_mark (&text->cursor_mark);
3995       
3996       while (!LAST_INDEX (text, text->cursor_mark) && 
3997              gdk_iswalnum (GTK_TEXT_INDEX(text, text->cursor_mark.index)))
3998         advance_mark (&text->cursor_mark);
3999     }
4000   else
4001     {
4002       while (!LAST_INDEX (text, text->cursor_mark) && 
4003              !isalnum (GTK_TEXT_INDEX(text, text->cursor_mark.index)))
4004         advance_mark (&text->cursor_mark);
4005       
4006       while (!LAST_INDEX (text, text->cursor_mark) && 
4007              isalnum (GTK_TEXT_INDEX(text, text->cursor_mark.index)))
4008         advance_mark (&text->cursor_mark);
4009     }
4010   
4011   find_cursor (text, TRUE);
4012   draw_cursor (text, FALSE);
4013 }
4014
4015 static void
4016 gtk_text_move_backward_word (GtkText *text)
4017 {
4018   text->cursor_virtual_x = 0;
4019   
4020   undraw_cursor (text, FALSE);
4021   
4022   if (text->use_wchar)
4023     {
4024       while ((text->cursor_mark.index > 0) &&
4025              !gdk_iswalnum (GTK_TEXT_INDEX(text, text->cursor_mark.index-1)))
4026         decrement_mark (&text->cursor_mark);
4027       
4028       while ((text->cursor_mark.index > 0) &&
4029              gdk_iswalnum (GTK_TEXT_INDEX(text, text->cursor_mark.index-1)))
4030         decrement_mark (&text->cursor_mark);
4031     }
4032   else
4033     {
4034       while ((text->cursor_mark.index > 0) &&
4035              !isalnum (GTK_TEXT_INDEX(text, text->cursor_mark.index-1)))
4036         decrement_mark (&text->cursor_mark);
4037       
4038       while ((text->cursor_mark.index > 0) &&
4039              isalnum (GTK_TEXT_INDEX(text, text->cursor_mark.index-1)))
4040         decrement_mark (&text->cursor_mark);
4041     }
4042   
4043   find_cursor (text, TRUE);
4044   draw_cursor (text, FALSE);
4045 }
4046
4047 static void 
4048 gtk_text_move_page (GtkOldEditable *old_editable,
4049                     gint            x,
4050                     gint            y)
4051 {
4052   if (y != 0)
4053     scroll_int (GTK_TEXT (old_editable), 
4054                 y * GTK_TEXT(old_editable)->vadj->page_increment);  
4055 }
4056
4057 static void 
4058 gtk_text_move_to_row (GtkOldEditable *old_editable,
4059                       gint            row)
4060 {
4061 }
4062
4063 static void 
4064 gtk_text_move_to_column (GtkOldEditable *old_editable,
4065                          gint            column)
4066 {
4067   GtkText *text;
4068   
4069   text = GTK_TEXT (old_editable);
4070   
4071   text->cursor_virtual_x = 0;   /* FIXME */
4072   
4073   undraw_cursor (text, FALSE);
4074   
4075   /* Move to the beginning of the line */
4076   while ((text->cursor_mark.index > 0) &&
4077          (GTK_TEXT_INDEX (text, text->cursor_mark.index - 1) != LINE_DELIM))
4078     decrement_mark (&text->cursor_mark);
4079   
4080   while (!LAST_INDEX (text, text->cursor_mark) &&
4081          (GTK_TEXT_INDEX (text, text->cursor_mark.index) != LINE_DELIM))
4082     {
4083       if (column > 0)
4084         column--;
4085       else if (column == 0)
4086         break;
4087       
4088       advance_mark (&text->cursor_mark);
4089     }
4090   
4091   find_cursor (text, TRUE);
4092   draw_cursor (text, FALSE);
4093 }
4094
4095 static void
4096 gtk_text_move_beginning_of_line (GtkText *text)
4097 {
4098   gtk_text_move_to_column (GTK_OLD_EDITABLE (text), 0);
4099   
4100 }
4101
4102 static void
4103 gtk_text_move_end_of_line (GtkText *text)
4104 {
4105   gtk_text_move_to_column (GTK_OLD_EDITABLE (text), -1);
4106 }
4107
4108 static void 
4109 gtk_text_kill_char (GtkOldEditable *old_editable,
4110                     gint            direction)
4111 {
4112   GtkText *text;
4113   
4114   text = GTK_TEXT (old_editable);
4115   
4116   if (old_editable->selection_start_pos != old_editable->selection_end_pos)
4117     gtk_editable_delete_selection (GTK_EDITABLE (old_editable));
4118   else
4119     {
4120       if (direction >= 0)
4121         {
4122           if (text->point.index + 1 <= TEXT_LENGTH (text))
4123             gtk_editable_delete_text (GTK_EDITABLE (old_editable), text->point.index, text->point.index + 1);
4124         }
4125       else
4126         {
4127           if (text->point.index > 0)
4128             gtk_editable_delete_text (GTK_EDITABLE (old_editable), text->point.index - 1, text->point.index);
4129         }
4130     }
4131 }
4132
4133 static void
4134 gtk_text_delete_forward_character (GtkText *text)
4135 {
4136   gtk_text_kill_char (GTK_OLD_EDITABLE (text), 1);
4137 }
4138
4139 static void
4140 gtk_text_delete_backward_character (GtkText *text)
4141 {
4142   gtk_text_kill_char (GTK_OLD_EDITABLE (text), -1);
4143 }
4144
4145 static void 
4146 gtk_text_kill_word (GtkOldEditable *old_editable,
4147                     gint            direction)
4148 {
4149   if (old_editable->selection_start_pos != old_editable->selection_end_pos)
4150     gtk_editable_delete_selection (GTK_EDITABLE (old_editable));
4151   else
4152     {
4153       gint old_pos = old_editable->current_pos;
4154       if (direction >= 0)
4155         {
4156           gtk_text_move_word (old_editable, 1);
4157           gtk_editable_delete_text (GTK_EDITABLE (old_editable), old_pos, old_editable->current_pos);
4158         }
4159       else
4160         {
4161           gtk_text_move_word (old_editable, -1);
4162           gtk_editable_delete_text (GTK_EDITABLE (old_editable), old_editable->current_pos, old_pos);
4163         }
4164     }
4165 }
4166
4167 static void
4168 gtk_text_delete_forward_word (GtkText *text)
4169 {
4170   gtk_text_kill_word (GTK_OLD_EDITABLE (text), 1);
4171 }
4172
4173 static void
4174 gtk_text_delete_backward_word (GtkText *text)
4175 {
4176   gtk_text_kill_word (GTK_OLD_EDITABLE (text), -1);
4177 }
4178
4179 static void 
4180 gtk_text_kill_line (GtkOldEditable *old_editable,
4181                     gint            direction)
4182 {
4183   gint old_pos = old_editable->current_pos;
4184   if (direction >= 0)
4185     {
4186       gtk_text_move_to_column (old_editable, -1);
4187       gtk_editable_delete_text (GTK_EDITABLE (old_editable), old_pos, old_editable->current_pos);
4188     }
4189   else
4190     {
4191       gtk_text_move_to_column (old_editable, 0);
4192       gtk_editable_delete_text (GTK_EDITABLE (old_editable), old_editable->current_pos, old_pos);
4193     }
4194 }
4195
4196 static void
4197 gtk_text_delete_line (GtkText *text)
4198 {
4199   gtk_text_move_to_column (GTK_OLD_EDITABLE (text), 0);
4200   gtk_text_kill_line (GTK_OLD_EDITABLE (text), 1);
4201 }
4202
4203 static void
4204 gtk_text_delete_to_line_end (GtkText *text)
4205 {
4206   gtk_text_kill_line (GTK_OLD_EDITABLE (text), 1);
4207 }
4208
4209 static void
4210 gtk_text_select_word (GtkText *text, guint32 time)
4211 {
4212   gint start_pos;
4213   gint end_pos;
4214   
4215   GtkOldEditable *old_editable;
4216   old_editable = GTK_OLD_EDITABLE (text);
4217   
4218   gtk_text_move_backward_word (text);
4219   start_pos = text->cursor_mark.index;
4220   
4221   gtk_text_move_forward_word (text);
4222   end_pos = text->cursor_mark.index;
4223   
4224   old_editable->has_selection = TRUE;
4225   gtk_text_set_selection (old_editable, start_pos, end_pos);
4226   gtk_old_editable_claim_selection (old_editable, start_pos != end_pos, time);
4227 }
4228
4229 static void
4230 gtk_text_select_line (GtkText *text, guint32 time)
4231 {
4232   gint start_pos;
4233   gint end_pos;
4234   
4235   GtkOldEditable *old_editable;
4236   old_editable = GTK_OLD_EDITABLE (text);
4237   
4238   gtk_text_move_beginning_of_line (text);
4239   start_pos = text->cursor_mark.index;
4240   
4241   gtk_text_move_end_of_line (text);
4242   gtk_text_move_forward_character (text);
4243   end_pos = text->cursor_mark.index;
4244   
4245   old_editable->has_selection = TRUE;
4246   gtk_text_set_selection (old_editable, start_pos, end_pos);
4247   gtk_old_editable_claim_selection (old_editable, start_pos != end_pos, time);
4248 }
4249
4250 /**********************************************************************/
4251 /*                            Scrolling                               */
4252 /**********************************************************************/
4253
4254 static void
4255 adjust_adj (GtkText* text, GtkAdjustment* adj)
4256 {
4257   gint height;
4258   
4259   gdk_window_get_size (text->text_area, NULL, &height);
4260   
4261   adj->step_increment = MIN (adj->upper, SCROLL_PIXELS);
4262   adj->page_increment = MIN (adj->upper, height - KEY_SCROLL_PIXELS);
4263   adj->page_size      = MIN (adj->upper, height);
4264   adj->value          = MIN (adj->value, adj->upper - adj->page_size);
4265   adj->value          = MAX (adj->value, 0.0);
4266   
4267   gtk_signal_emit_by_name (GTK_OBJECT (adj), "changed");
4268 }
4269
4270 static gint
4271 set_vertical_scroll_iterator (GtkText* text, LineParams* lp, void* data)
4272 {
4273   SetVerticalScrollData *svdata = (SetVerticalScrollData *) data;
4274   
4275   if ((text->first_line_start_index >= lp->start.index) &&
4276       (text->first_line_start_index <= lp->end.index))
4277     {
4278       svdata->mark = lp->start;
4279   
4280       if (text->first_line_start_index == lp->start.index)
4281         {
4282           text->first_onscreen_ver_pixel = svdata->pixel_height + text->first_cut_pixels;
4283         }
4284       else
4285         {
4286           text->first_onscreen_ver_pixel = svdata->pixel_height;
4287           text->first_cut_pixels = 0;
4288         }
4289       
4290       text->vadj->value = text->first_onscreen_ver_pixel;
4291     }
4292   
4293   svdata->pixel_height += LINE_HEIGHT (*lp);
4294   
4295   return FALSE;
4296 }
4297
4298 static gint
4299 set_vertical_scroll_find_iterator (GtkText* text, LineParams* lp, void* data)
4300 {
4301   SetVerticalScrollData *svdata = (SetVerticalScrollData *) data;
4302   gint return_val;
4303   
4304   if (svdata->pixel_height <= (gint) text->vadj->value &&
4305       svdata->pixel_height + LINE_HEIGHT(*lp) > (gint) text->vadj->value)
4306     {
4307       svdata->mark = lp->start;
4308       
4309       text->first_cut_pixels = (gint)text->vadj->value - svdata->pixel_height;
4310       text->first_onscreen_ver_pixel = svdata->pixel_height;
4311       text->first_line_start_index = lp->start.index;
4312       
4313       return_val = TRUE;
4314     }
4315   else
4316     {
4317       svdata->pixel_height += LINE_HEIGHT (*lp);
4318       
4319       return_val = FALSE;
4320     }
4321   
4322   return return_val;
4323 }
4324
4325 static GtkPropertyMark
4326 set_vertical_scroll (GtkText* text)
4327 {
4328   GtkPropertyMark mark = find_mark (text, 0);
4329   SetVerticalScrollData data;
4330   gint height;
4331   gint orig_value;
4332   
4333   data.pixel_height = 0;
4334   line_params_iterate (text, &mark, NULL, FALSE, &data, set_vertical_scroll_iterator);
4335   
4336   text->vadj->upper = data.pixel_height;
4337   orig_value = (gint) text->vadj->value;
4338   
4339   gdk_window_get_size (text->text_area, NULL, &height);
4340   
4341   text->vadj->step_increment = MIN (text->vadj->upper, SCROLL_PIXELS);
4342   text->vadj->page_increment = MIN (text->vadj->upper, height - KEY_SCROLL_PIXELS);
4343   text->vadj->page_size      = MIN (text->vadj->upper, height);
4344   text->vadj->value          = MIN (text->vadj->value, text->vadj->upper - text->vadj->page_size);
4345   text->vadj->value          = MAX (text->vadj->value, 0.0);
4346   
4347   text->last_ver_value = (gint)text->vadj->value;
4348   
4349   gtk_signal_emit_by_name (GTK_OBJECT (text->vadj), "changed");
4350   
4351   if (text->vadj->value != orig_value)
4352     {
4353       /* We got clipped, and don't really know which line to put first. */
4354       data.pixel_height = 0;
4355       data.last_didnt_wrap = TRUE;
4356       
4357       line_params_iterate (text, &mark, NULL,
4358                            FALSE, &data,
4359                            set_vertical_scroll_find_iterator);
4360     }
4361
4362   return data.mark;
4363 }
4364
4365 static void
4366 scroll_int (GtkText* text, gint diff)
4367 {
4368   gdouble upper;
4369   
4370   text->vadj->value += diff;
4371   
4372   upper = text->vadj->upper - text->vadj->page_size;
4373   text->vadj->value = MIN (text->vadj->value, upper);
4374   text->vadj->value = MAX (text->vadj->value, 0.0);
4375   
4376   gtk_signal_emit_by_name (GTK_OBJECT (text->vadj), "value_changed");
4377 }
4378
4379 static void 
4380 process_exposes (GtkText *text)
4381 {
4382   GdkEvent *event;
4383   
4384   /* Make sure graphics expose events are processed before scrolling
4385    * again */
4386   
4387   while ((event = gdk_event_get_graphics_expose (text->text_area)) != NULL)
4388     {
4389       gtk_widget_send_expose (GTK_WIDGET (text), event);
4390       if (event->expose.count == 0)
4391         {
4392           gdk_event_free (event);
4393           break;
4394         }
4395       gdk_event_free (event);
4396     }
4397 }
4398
4399 static gint last_visible_line_height (GtkText* text)
4400 {
4401   GList *cache = text->line_start_cache;
4402   gint height;
4403   
4404   gdk_window_get_size (text->text_area, NULL, &height);
4405   
4406   for (; cache->next; cache = cache->next)
4407     if (pixel_height_of(text, cache->next) > height)
4408       break;
4409   
4410   if (cache)
4411     return pixel_height_of(text, cache) - 1;
4412   else
4413     return 0;
4414 }
4415
4416 static gint first_visible_line_height (GtkText* text)
4417 {
4418   if (text->first_cut_pixels)
4419     return pixel_height_of(text, text->line_start_cache) + 1;
4420   else
4421     return 1;
4422 }
4423
4424 static void
4425 scroll_down (GtkText* text, gint diff0)
4426 {
4427   GdkRectangle rect;
4428   gint real_diff = 0;
4429   gint width, height;
4430   
4431   text->first_onscreen_ver_pixel += diff0;
4432   
4433   while (diff0-- > 0)
4434     {
4435       g_assert (text->line_start_cache);
4436       
4437       if (text->first_cut_pixels < LINE_HEIGHT(CACHE_DATA(text->line_start_cache)) - 1)
4438         {
4439           text->first_cut_pixels += 1;
4440         }
4441       else
4442         {
4443           text->first_cut_pixels = 0;
4444           
4445           text->line_start_cache = text->line_start_cache->next;
4446           
4447           text->first_line_start_index =
4448             CACHE_DATA(text->line_start_cache).start.index;
4449           
4450           if (!text->line_start_cache->next)
4451             fetch_lines_forward (text, 1);
4452         }
4453       
4454       real_diff += 1;
4455     }
4456   
4457   gdk_window_get_size (text->text_area, &width, &height);
4458   if (height > real_diff)
4459     gdk_draw_pixmap (text->text_area,
4460                      text->gc,
4461                      text->text_area,
4462                      0,
4463                      real_diff,
4464                      0,
4465                      0,
4466                      width,
4467                      height - real_diff);
4468   
4469   rect.x      = 0;
4470   rect.y      = MAX (0, height - real_diff);
4471   rect.width  = width;
4472   rect.height = MIN (height, real_diff);
4473   
4474   expose_text (text, &rect, FALSE);
4475   gtk_text_draw_focus ( (GtkWidget *) text);
4476   
4477   if (text->current_line)
4478     {
4479       gint cursor_min;
4480       
4481       text->cursor_pos_y -= real_diff;
4482       cursor_min = drawn_cursor_min(text);
4483       
4484       if (cursor_min < 0)
4485         find_mouse_cursor (text, text->cursor_pos_x,
4486                            first_visible_line_height (text));
4487     }
4488   
4489   if (height > real_diff)
4490     process_exposes (text);
4491 }
4492
4493 static void
4494 scroll_up (GtkText* text, gint diff0)
4495 {
4496   gint real_diff = 0;
4497   GdkRectangle rect;
4498   gint width, height;
4499   
4500   text->first_onscreen_ver_pixel += diff0;
4501   
4502   while (diff0++ < 0)
4503     {
4504       g_assert (text->line_start_cache);
4505       
4506       if (text->first_cut_pixels > 0)
4507         {
4508           text->first_cut_pixels -= 1;
4509         }
4510       else
4511         {
4512           if (!text->line_start_cache->prev)
4513             fetch_lines_backward (text);
4514           
4515           text->line_start_cache = text->line_start_cache->prev;
4516           
4517           text->first_line_start_index =
4518             CACHE_DATA(text->line_start_cache).start.index;
4519           
4520           text->first_cut_pixels = LINE_HEIGHT(CACHE_DATA(text->line_start_cache)) - 1;
4521         }
4522       
4523       real_diff += 1;
4524     }
4525   
4526   gdk_window_get_size (text->text_area, &width, &height);
4527   if (height > real_diff)
4528     gdk_draw_pixmap (text->text_area,
4529                      text->gc,
4530                      text->text_area,
4531                      0,
4532                      0,
4533                      0,
4534                      real_diff,
4535                      width,
4536                      height - real_diff);
4537   
4538   rect.x      = 0;
4539   rect.y      = 0;
4540   rect.width  = width;
4541   rect.height = MIN (height, real_diff);
4542   
4543   expose_text (text, &rect, FALSE);
4544   gtk_text_draw_focus ( (GtkWidget *) text);
4545   
4546   if (text->current_line)
4547     {
4548       gint cursor_max;
4549       gint height;
4550       
4551       text->cursor_pos_y += real_diff;
4552       cursor_max = drawn_cursor_max(text);
4553       gdk_window_get_size (text->text_area, NULL, &height);
4554       
4555       if (cursor_max >= height)
4556         find_mouse_cursor (text, text->cursor_pos_x,
4557                            last_visible_line_height (text));
4558     }
4559   
4560   if (height > real_diff)
4561     process_exposes (text);
4562 }
4563
4564 /**********************************************************************/
4565 /*                            Display Code                            */
4566 /**********************************************************************/
4567
4568 /* Assumes mark starts a line.  Calculates the height, width, and
4569  * displayable character count of a single DISPLAYABLE line.  That
4570  * means that in line-wrap mode, this does may not compute the
4571  * properties of an entire line. */
4572 static LineParams
4573 find_line_params (GtkText* text,
4574                   const GtkPropertyMark* mark,
4575                   const PrevTabCont *tab_cont,
4576                   PrevTabCont *next_cont)
4577 {
4578   LineParams lp;
4579   TabStopMark tab_mark = tab_cont->tab_start;
4580   guint max_display_pixels;
4581   GdkWChar ch;
4582   gint ch_width;
4583   GdkFont *font;
4584   
4585   gdk_window_get_size (text->text_area, (gint*) &max_display_pixels, NULL);
4586   max_display_pixels -= LINE_WRAP_ROOM;
4587   
4588   lp.wraps             = 0;
4589   lp.tab_cont          = *tab_cont;
4590   lp.start             = *mark;
4591   lp.end               = *mark;
4592   lp.pixel_width       = tab_cont->pixel_offset;
4593   lp.displayable_chars = 0;
4594   lp.font_ascent       = 0;
4595   lp.font_descent      = 0;
4596   
4597   init_tab_cont (text, next_cont);
4598   
4599   while (!LAST_INDEX(text, lp.end))
4600     {
4601       g_assert (lp.end.property);
4602       
4603       ch   = GTK_TEXT_INDEX (text, lp.end.index);
4604       font = MARK_CURRENT_FONT (text, &lp.end);
4605
4606       if (ch == LINE_DELIM)
4607         {
4608           /* Newline doesn't count in computation of line height, even
4609            * if its in a bigger font than the rest of the line.  Unless,
4610            * of course, there are no other characters. */
4611           
4612           if (!lp.font_ascent && !lp.font_descent)
4613             {
4614               lp.font_ascent = font->ascent;
4615               lp.font_descent = font->descent;
4616             }
4617           
4618           lp.tab_cont_next = *next_cont;
4619           
4620           return lp;
4621         }
4622       
4623       ch_width = find_char_width (text, &lp.end, &tab_mark);
4624       
4625       if ((ch_width + lp.pixel_width > max_display_pixels) &&
4626           (lp.end.index > lp.start.index))
4627         {
4628           lp.wraps = 1;
4629           
4630           if (text->line_wrap)
4631             {
4632               next_cont->tab_start    = tab_mark;
4633               next_cont->pixel_offset = 0;
4634               
4635               if (ch == '\t')
4636                 {
4637                   /* Here's the tough case, a tab is wrapping. */
4638                   gint pixels_avail = max_display_pixels - lp.pixel_width;
4639                   gint space_width  = MARK_CURRENT_TEXT_FONT(text, &lp.end)->char_widths[' '];
4640                   gint spaces_avail = pixels_avail / space_width;
4641                   
4642                   if (spaces_avail == 0)
4643                     {
4644                       decrement_mark (&lp.end);
4645                     }
4646                   else
4647                     {
4648                       advance_tab_mark (text, &next_cont->tab_start, '\t');
4649                       next_cont->pixel_offset = space_width * (tab_mark.to_next_tab -
4650                                                                spaces_avail);
4651                       lp.displayable_chars += 1;
4652                     }
4653                 }
4654               else
4655                 {
4656                   if (text->word_wrap)
4657                     {
4658                       GtkPropertyMark saved_mark = lp.end;
4659                       guint saved_characters = lp.displayable_chars;
4660                       
4661                       lp.displayable_chars += 1;
4662                       
4663                       if (text->use_wchar)
4664                         {
4665                           while (!gdk_iswspace (GTK_TEXT_INDEX (text, lp.end.index)) &&
4666                                  (lp.end.index > lp.start.index))
4667                             {
4668                               decrement_mark (&lp.end);
4669                               lp.displayable_chars -= 1;
4670                             }
4671                         }
4672                       else
4673                         {
4674                           while (!isspace(GTK_TEXT_INDEX (text, lp.end.index)) &&
4675                                  (lp.end.index > lp.start.index))
4676                             {
4677                               decrement_mark (&lp.end);
4678                               lp.displayable_chars -= 1;
4679                             }
4680                         }
4681                       
4682                       /* If whole line is one word, revert to char wrapping */
4683                       if (lp.end.index == lp.start.index)
4684                         {
4685                           lp.end = saved_mark;
4686                           lp.displayable_chars = saved_characters;
4687                           decrement_mark (&lp.end);
4688                         }
4689                     }
4690                   else
4691                     {
4692                       /* Don't include this character, it will wrap. */
4693                       decrement_mark (&lp.end);
4694                     }
4695                 }
4696               
4697               lp.tab_cont_next = *next_cont;
4698               
4699               return lp;
4700             }
4701         }
4702       else
4703         {
4704           lp.displayable_chars += 1;
4705         }
4706       
4707       lp.font_ascent = MAX (font->ascent, lp.font_ascent);
4708       lp.font_descent = MAX (font->descent, lp.font_descent);
4709       lp.pixel_width  += ch_width;
4710       
4711       advance_mark(&lp.end);
4712       advance_tab_mark (text, &tab_mark, ch);
4713     }
4714   
4715   if (LAST_INDEX(text, lp.start))
4716     {
4717       /* Special case, empty last line. */
4718       font = MARK_CURRENT_FONT (text, &lp.end);
4719
4720       lp.font_ascent = font->ascent;
4721       lp.font_descent = font->descent;
4722     }
4723   
4724   lp.tab_cont_next = *next_cont;
4725   
4726   return lp;
4727 }
4728
4729 static void
4730 expand_scratch_buffer (GtkText* text, guint len)
4731 {
4732   if (len >= text->scratch_buffer_len)
4733     {
4734       guint i = 1;
4735       
4736       while (i <= len && i < MIN_GAP_SIZE) i <<= 1;
4737       
4738       if (text->use_wchar)
4739         {
4740           if (text->scratch_buffer.wc)
4741             text->scratch_buffer.wc = g_new (GdkWChar, i);
4742           else
4743             text->scratch_buffer.wc = g_realloc (text->scratch_buffer.wc,
4744                                               i*sizeof (GdkWChar));
4745         }
4746       else
4747         {
4748           if (text->scratch_buffer.ch)
4749             text->scratch_buffer.ch = g_new (guchar, i);
4750           else
4751             text->scratch_buffer.ch = g_realloc (text->scratch_buffer.ch, i);
4752         }
4753       
4754       text->scratch_buffer_len = i;
4755     }
4756 }
4757
4758 /* Side effect: modifies text->gc
4759  */
4760 static void
4761 draw_bg_rect (GtkText* text, GtkPropertyMark *mark,
4762               gint x, gint y, gint width, gint height,
4763               gboolean already_cleared)
4764 {
4765   GtkOldEditable *old_editable = GTK_OLD_EDITABLE (text);
4766
4767   if ((mark->index >= MIN(old_editable->selection_start_pos, old_editable->selection_end_pos) &&
4768        mark->index < MAX(old_editable->selection_start_pos, old_editable->selection_end_pos)))
4769     {
4770       gtk_paint_flat_box(GTK_WIDGET(text)->style, text->text_area,
4771                          old_editable->has_selection ?
4772                             GTK_STATE_SELECTED : GTK_STATE_ACTIVE, 
4773                          GTK_SHADOW_NONE,
4774                          NULL, GTK_WIDGET(text), "text",
4775                          x, y, width, height);
4776     }
4777   else if (!gdk_color_equal(MARK_CURRENT_BACK (text, mark),
4778                             &GTK_WIDGET(text)->style->base[GTK_WIDGET_STATE (text)]))
4779     {
4780       gdk_gc_set_foreground (text->gc, MARK_CURRENT_BACK (text, mark));
4781
4782       gdk_draw_rectangle (text->text_area,
4783                           text->gc,
4784                           TRUE, x, y, width, height);
4785     }
4786   else if (GTK_WIDGET (text)->style->bg_pixmap[GTK_STATE_NORMAL])
4787     {
4788       GdkRectangle rect;
4789       
4790       rect.x = x;
4791       rect.y = y;
4792       rect.width = width;
4793       rect.height = height;
4794       
4795       clear_area (text, &rect);
4796     }
4797   else if (!already_cleared)
4798     gdk_window_clear_area (text->text_area, x, y, width, height);
4799 }
4800
4801 static void
4802 draw_line (GtkText* text,
4803            gint pixel_start_height,
4804            LineParams* lp)
4805 {
4806   GdkGCValues gc_values;
4807   gint i;
4808   gint len = 0;
4809   guint running_offset = lp->tab_cont.pixel_offset;
4810   union { GdkWChar *wc; guchar *ch; } buffer;
4811   GdkGC *fg_gc;
4812   
4813   GtkOldEditable *old_editable = GTK_OLD_EDITABLE (text);
4814   
4815   guint selection_start_pos = MIN (old_editable->selection_start_pos, old_editable->selection_end_pos);
4816   guint selection_end_pos = MAX (old_editable->selection_start_pos, old_editable->selection_end_pos);
4817   
4818   GtkPropertyMark mark = lp->start;
4819   TabStopMark tab_mark = lp->tab_cont.tab_start;
4820   gint pixel_height = pixel_start_height + lp->font_ascent;
4821   guint chars = lp->displayable_chars;
4822   
4823   /* First provide a contiguous segment of memory.  This makes reading
4824    * the code below *much* easier, and only incurs the cost of copying
4825    * when the line being displayed spans the gap. */
4826   if (mark.index <= text->gap_position &&
4827       mark.index + chars > text->gap_position)
4828     {
4829       expand_scratch_buffer (text, chars);
4830       
4831       if (text->use_wchar)
4832         {
4833           for (i = 0; i < chars; i += 1)
4834             text->scratch_buffer.wc[i] = GTK_TEXT_INDEX(text, mark.index + i);
4835           buffer.wc = text->scratch_buffer.wc;
4836         }
4837       else
4838         {
4839           for (i = 0; i < chars; i += 1)
4840             text->scratch_buffer.ch[i] = GTK_TEXT_INDEX(text, mark.index + i);
4841           buffer.ch = text->scratch_buffer.ch;
4842         }
4843     }
4844   else
4845     {
4846       if (text->use_wchar)
4847         {
4848           if (mark.index >= text->gap_position)
4849             buffer.wc = text->text.wc + mark.index + text->gap_size;
4850           else
4851             buffer.wc = text->text.wc + mark.index;
4852         }
4853       else
4854         {
4855           if (mark.index >= text->gap_position)
4856             buffer.ch = text->text.ch + mark.index + text->gap_size;
4857           else
4858             buffer.ch = text->text.ch + mark.index;
4859         }
4860     }
4861   
4862   
4863   if (running_offset > 0)
4864     {
4865       draw_bg_rect (text, &mark, 0, pixel_start_height, running_offset,
4866                     LINE_HEIGHT (*lp), TRUE);
4867     }
4868   
4869   while (chars > 0)
4870     {
4871       len = 0;
4872       if ((text->use_wchar && buffer.wc[0] != '\t') ||
4873           (!text->use_wchar && buffer.ch[0] != '\t'))
4874         {
4875           union { GdkWChar *wc; guchar *ch; } next_tab;
4876           gint pixel_width;
4877           GdkFont *font;
4878
4879           next_tab.wc = NULL;
4880           if (text->use_wchar)
4881             for (i=0; i<chars; i++)
4882               {
4883                 if (buffer.wc[i] == '\t')
4884                   {
4885                     next_tab.wc = buffer.wc + i;
4886                     break;
4887                   }
4888               }
4889           else
4890             next_tab.ch = memchr (buffer.ch, '\t', chars);
4891
4892           len = MIN (MARK_CURRENT_PROPERTY (&mark)->length - mark.offset, chars);
4893           
4894           if (text->use_wchar)
4895             {
4896               if (next_tab.wc)
4897                 len = MIN (len, next_tab.wc - buffer.wc);
4898             }
4899           else
4900             {
4901               if (next_tab.ch)
4902                 len = MIN (len, next_tab.ch - buffer.ch);
4903             }
4904
4905           if (mark.index < selection_start_pos)
4906             len = MIN (len, selection_start_pos - mark.index);
4907           else if (mark.index < selection_end_pos)
4908             len = MIN (len, selection_end_pos - mark.index);
4909
4910           font = MARK_CURRENT_FONT (text, &mark);
4911           if (font->type == GDK_FONT_FONT)
4912             {
4913               gdk_gc_set_font (text->gc, font);
4914               gdk_gc_get_values (text->gc, &gc_values);
4915               if (text->use_wchar)
4916                 pixel_width = gdk_text_width_wc (gc_values.font,
4917                                                  buffer.wc, len);
4918               else
4919               pixel_width = gdk_text_width (gc_values.font,
4920                                               buffer.ch, len);
4921             }
4922           else
4923             {
4924               if (text->use_wchar)
4925                 pixel_width = gdk_text_width_wc (font, buffer.wc, len);
4926               else
4927                 pixel_width = gdk_text_width (font, buffer.ch, len);
4928             }
4929           
4930           draw_bg_rect (text, &mark, running_offset, pixel_start_height,
4931                         pixel_width, LINE_HEIGHT (*lp), TRUE);
4932           
4933           if ((mark.index >= selection_start_pos) && 
4934               (mark.index < selection_end_pos))
4935             {
4936               if (old_editable->has_selection)
4937                 fg_gc = GTK_WIDGET(text)->style->text_gc[GTK_STATE_SELECTED];
4938               else
4939                 fg_gc = GTK_WIDGET(text)->style->text_gc[GTK_STATE_ACTIVE];
4940             }
4941           else
4942             {
4943               gdk_gc_set_foreground (text->gc, MARK_CURRENT_FORE (text, &mark));
4944               fg_gc = text->gc;
4945             }
4946
4947           if (text->use_wchar)
4948             gdk_draw_text_wc (text->text_area, MARK_CURRENT_FONT (text, &mark),
4949                               fg_gc,
4950                               running_offset,
4951                               pixel_height,
4952                               buffer.wc,
4953                               len);
4954           else
4955             gdk_draw_text (text->text_area, MARK_CURRENT_FONT (text, &mark),
4956                            fg_gc,
4957                            running_offset,
4958                            pixel_height,
4959                            buffer.ch,
4960                            len);
4961           
4962           running_offset += pixel_width;
4963           
4964           advance_tab_mark_n (text, &tab_mark, len);
4965         }
4966       else
4967         {
4968           gint pixels_remaining;
4969           gint space_width;
4970           gint spaces_avail;
4971               
4972           len = 1;
4973           
4974           gdk_window_get_size (text->text_area, &pixels_remaining, NULL);
4975           pixels_remaining -= (LINE_WRAP_ROOM + running_offset);
4976           
4977           space_width = MARK_CURRENT_TEXT_FONT(text, &mark)->char_widths[' '];
4978           
4979           spaces_avail = pixels_remaining / space_width;
4980           spaces_avail = MIN (spaces_avail, tab_mark.to_next_tab);
4981
4982           draw_bg_rect (text, &mark, running_offset, pixel_start_height,
4983                         spaces_avail * space_width, LINE_HEIGHT (*lp), TRUE);
4984
4985           running_offset += tab_mark.to_next_tab *
4986             MARK_CURRENT_TEXT_FONT(text, &mark)->char_widths[' '];
4987
4988           advance_tab_mark (text, &tab_mark, '\t');
4989         }
4990       
4991       advance_mark_n (&mark, len);
4992       if (text->use_wchar)
4993         buffer.wc += len;
4994       else
4995         buffer.ch += len;
4996       chars -= len;
4997     }
4998 }
4999
5000 static void
5001 draw_line_wrap (GtkText* text, guint height /* baseline height */)
5002 {
5003   gint width;
5004   GdkPixmap *bitmap;
5005   gint bitmap_width;
5006   gint bitmap_height;
5007   
5008   if (text->line_wrap)
5009     {
5010       bitmap = text->line_wrap_bitmap;
5011       bitmap_width = line_wrap_width;
5012       bitmap_height = line_wrap_height;
5013     }
5014   else
5015     {
5016       bitmap = text->line_arrow_bitmap;
5017       bitmap_width = line_arrow_width;
5018       bitmap_height = line_arrow_height;
5019     }
5020   
5021   gdk_window_get_size (text->text_area, &width, NULL);
5022   width -= LINE_WRAP_ROOM;
5023   
5024   gdk_gc_set_stipple (text->gc,
5025                       bitmap);
5026   
5027   gdk_gc_set_fill (text->gc, GDK_STIPPLED);
5028   
5029   gdk_gc_set_foreground (text->gc, &GTK_WIDGET (text)->style->text[GTK_STATE_NORMAL]);
5030   
5031   gdk_gc_set_ts_origin (text->gc,
5032                         width + 1,
5033                         height - bitmap_height - 1);
5034   
5035   gdk_draw_rectangle (text->text_area,
5036                       text->gc,
5037                       TRUE,
5038                       width + 1,
5039                       height - bitmap_height - 1 /* one pixel above the baseline. */,
5040                       bitmap_width,
5041                       bitmap_height);
5042   
5043   gdk_gc_set_ts_origin (text->gc, 0, 0);
5044   
5045   gdk_gc_set_fill (text->gc, GDK_SOLID);
5046 }
5047
5048 static void
5049 undraw_cursor (GtkText* text, gint absolute)
5050 {
5051   GtkOldEditable *old_editable = (GtkOldEditable *) text;
5052
5053   TDEBUG (("in undraw_cursor\n"));
5054   
5055   if (absolute)
5056     text->cursor_drawn_level = 0;
5057   
5058   if ((text->cursor_drawn_level ++ == 0) &&
5059       (old_editable->selection_start_pos == old_editable->selection_end_pos) &&
5060       GTK_WIDGET_DRAWABLE (text) && text->line_start_cache)
5061     {
5062       GdkFont* font;
5063       
5064       g_assert(text->cursor_mark.property);
5065
5066       font = MARK_CURRENT_FONT(text, &text->cursor_mark);
5067
5068       draw_bg_rect (text, &text->cursor_mark, 
5069                     text->cursor_pos_x,
5070                     text->cursor_pos_y - text->cursor_char_offset - font->ascent,
5071                     1, font->ascent + 1, FALSE);
5072       
5073       if (text->cursor_char)
5074         {
5075           if (font->type == GDK_FONT_FONT)
5076             gdk_gc_set_font (text->gc, font);
5077
5078           gdk_gc_set_foreground (text->gc, MARK_CURRENT_FORE (text, &text->cursor_mark));
5079
5080           gdk_draw_text_wc (text->text_area, font,
5081                          text->gc,
5082                          text->cursor_pos_x,
5083                          text->cursor_pos_y - text->cursor_char_offset,
5084                          &text->cursor_char,
5085                          1);
5086         }
5087     }
5088 }
5089
5090 static gint
5091 drawn_cursor_min (GtkText* text)
5092 {
5093   GdkFont* font;
5094   
5095   g_assert(text->cursor_mark.property);
5096   
5097   font = MARK_CURRENT_FONT(text, &text->cursor_mark);
5098   
5099   return text->cursor_pos_y - text->cursor_char_offset - font->ascent;
5100 }
5101
5102 static gint
5103 drawn_cursor_max (GtkText* text)
5104 {
5105   GdkFont* font;
5106   
5107   g_assert(text->cursor_mark.property);
5108   
5109   font = MARK_CURRENT_FONT(text, &text->cursor_mark);
5110   
5111   return text->cursor_pos_y - text->cursor_char_offset;
5112 }
5113
5114 static void
5115 draw_cursor (GtkText* text, gint absolute)
5116 {
5117   GtkOldEditable *old_editable = (GtkOldEditable *)text;
5118   
5119   TDEBUG (("in draw_cursor\n"));
5120   
5121   if (absolute)
5122     text->cursor_drawn_level = 1;
5123   
5124   if ((--text->cursor_drawn_level == 0) &&
5125       old_editable->editable &&
5126       (old_editable->selection_start_pos == old_editable->selection_end_pos) &&
5127       GTK_WIDGET_DRAWABLE (text) && text->line_start_cache)
5128     {
5129       GdkFont* font;
5130       
5131       g_assert (text->cursor_mark.property);
5132
5133       font = MARK_CURRENT_FONT (text, &text->cursor_mark);
5134
5135       gdk_gc_set_foreground (text->gc, &GTK_WIDGET (text)->style->text[GTK_STATE_NORMAL]);
5136       
5137       gdk_draw_line (text->text_area, text->gc, text->cursor_pos_x,
5138                      text->cursor_pos_y - text->cursor_char_offset,
5139                      text->cursor_pos_x,
5140                      text->cursor_pos_y - text->cursor_char_offset - font->ascent);
5141     }
5142 }
5143
5144 static GdkGC *
5145 create_bg_gc (GtkText *text)
5146 {
5147   GdkGCValues values;
5148   
5149   values.tile = GTK_WIDGET (text)->style->bg_pixmap[GTK_STATE_NORMAL];
5150   values.fill = GDK_TILED;
5151
5152   return gdk_gc_new_with_values (text->text_area, &values,
5153                                  GDK_GC_FILL | GDK_GC_TILE);
5154 }
5155
5156 static void
5157 clear_area (GtkText *text, GdkRectangle *area)
5158 {
5159   GtkWidget *widget = GTK_WIDGET (text);
5160   
5161   if (text->bg_gc)
5162     {
5163       gint width, height;
5164       
5165       gdk_window_get_size (widget->style->bg_pixmap[GTK_STATE_NORMAL], &width, &height);
5166       
5167       gdk_gc_set_ts_origin (text->bg_gc,
5168                             (- text->first_onscreen_hor_pixel) % width,
5169                             (- text->first_onscreen_ver_pixel) % height);
5170
5171       gdk_draw_rectangle (text->text_area, text->bg_gc, TRUE,
5172                           area->x, area->y, area->width, area->height);
5173     }
5174   else
5175     gdk_window_clear_area (text->text_area, area->x, area->y, area->width, area->height);
5176 }
5177
5178 static void
5179 expose_text (GtkText* text, GdkRectangle *area, gboolean cursor)
5180 {
5181   GList *cache = text->line_start_cache;
5182   gint pixels = - text->first_cut_pixels;
5183   gint min_y = MAX (0, area->y);
5184   gint max_y = MAX (0, area->y + area->height);
5185   gint height;
5186   
5187   gdk_window_get_size (text->text_area, NULL, &height);
5188   max_y = MIN (max_y, height);
5189   
5190   TDEBUG (("in expose x=%d y=%d w=%d h=%d\n", area->x, area->y, area->width, area->height));
5191   
5192   clear_area (text, area);
5193   
5194   for (; pixels < height; cache = cache->next)
5195     {
5196       if (pixels < max_y && (pixels + (gint)LINE_HEIGHT(CACHE_DATA(cache))) >= min_y)
5197         {
5198           draw_line (text, pixels, &CACHE_DATA(cache));
5199           
5200           if (CACHE_DATA(cache).wraps)
5201             draw_line_wrap (text, pixels + CACHE_DATA(cache).font_ascent);
5202         }
5203       
5204       if (cursor && GTK_WIDGET_HAS_FOCUS (text))
5205         {
5206           if (CACHE_DATA(cache).start.index <= text->cursor_mark.index &&
5207               CACHE_DATA(cache).end.index >= text->cursor_mark.index)
5208             {
5209               /* We undraw and draw the cursor here to get the drawn
5210                * level right ... FIXME - maybe the second parameter
5211                * of draw_cursor should work differently
5212                */
5213               undraw_cursor (text, FALSE);
5214               draw_cursor (text, FALSE);
5215             }
5216         }
5217       
5218       pixels += LINE_HEIGHT(CACHE_DATA(cache));
5219       
5220       if (!cache->next)
5221         {
5222           fetch_lines_forward (text, 1);
5223           
5224           if (!cache->next)
5225             break;
5226         }
5227     }
5228 }
5229
5230 static void 
5231 gtk_text_update_text (GtkOldEditable    *old_editable,
5232                       gint               start_pos,
5233                       gint               end_pos)
5234 {
5235   GtkText *text = GTK_TEXT (old_editable);
5236   
5237   GList *cache = text->line_start_cache;
5238   gint pixels = - text->first_cut_pixels;
5239   GdkRectangle area;
5240   gint width;
5241   gint height;
5242   
5243   if (end_pos < 0)
5244     end_pos = TEXT_LENGTH (text);
5245   
5246   if (end_pos < start_pos)
5247     return;
5248   
5249   gdk_window_get_size (text->text_area, &width, &height);
5250   area.x = 0;
5251   area.y = -1;
5252   area.width = width;
5253   area.height = 0;
5254   
5255   TDEBUG (("in expose span start=%d stop=%d\n", start_pos, end_pos));
5256   
5257   for (; pixels < height; cache = cache->next)
5258     {
5259       if (CACHE_DATA(cache).start.index < end_pos)
5260         {
5261           if (CACHE_DATA(cache).end.index >= start_pos)
5262             {
5263               if (area.y < 0)
5264                 area.y = MAX(0,pixels);
5265               area.height = pixels + LINE_HEIGHT(CACHE_DATA(cache)) - area.y;
5266             }
5267         }
5268       else
5269         break;
5270       
5271       pixels += LINE_HEIGHT(CACHE_DATA(cache));
5272       
5273       if (!cache->next)
5274         {
5275           fetch_lines_forward (text, 1);
5276           
5277           if (!cache->next)
5278             break;
5279         }
5280     }
5281   
5282   if (area.y >= 0)
5283     expose_text (text, &area, TRUE);
5284 }
5285
5286 static void
5287 recompute_geometry (GtkText* text)
5288 {
5289   GtkPropertyMark mark, start_mark;
5290   GList *new_lines;
5291   gint height;
5292   gint width;
5293   
5294   free_cache (text);
5295   
5296   mark = start_mark = set_vertical_scroll (text);
5297
5298   /* We need a real start of a line when calling fetch_lines().
5299    * not the start of a wrapped line.
5300    */
5301   while (mark.index > 0 &&
5302          GTK_TEXT_INDEX (text, mark.index - 1) != LINE_DELIM)
5303     decrement_mark (&mark);
5304
5305   gdk_window_get_size (text->text_area, &width, &height);
5306
5307   /* Fetch an entire line, to make sure that we get all the text
5308    * we backed over above, in addition to enough text to fill up
5309    * the space vertically
5310    */
5311
5312   new_lines = fetch_lines (text,
5313                            &mark,
5314                            NULL,
5315                            FetchLinesCount,
5316                            1);
5317
5318   mark = CACHE_DATA (g_list_last (new_lines)).end;
5319   if (!LAST_INDEX (text, mark))
5320     {
5321       advance_mark (&mark);
5322
5323       new_lines = g_list_concat (new_lines, 
5324                                  fetch_lines (text,
5325                                               &mark,
5326                                               NULL,
5327                                               FetchLinesPixels,
5328                                               height + text->first_cut_pixels));
5329     }
5330
5331   /* Now work forward to the actual first onscreen line */
5332
5333   while (CACHE_DATA (new_lines).start.index < start_mark.index)
5334     new_lines = new_lines->next;
5335   
5336   text->line_start_cache = new_lines;
5337   
5338   find_cursor (text, TRUE);
5339 }
5340
5341 /**********************************************************************/
5342 /*                            Selection                               */
5343 /**********************************************************************/
5344
5345 static void 
5346 gtk_text_set_selection  (GtkOldEditable  *old_editable,
5347                          gint             start,
5348                          gint             end)
5349 {
5350   GtkText *text = GTK_TEXT (old_editable);
5351   
5352   guint start1, end1, start2, end2;
5353   
5354   if (end < 0)
5355     end = TEXT_LENGTH (text);
5356   
5357   start1 = MIN(start,end);
5358   end1 = MAX(start,end);
5359   start2 = MIN(old_editable->selection_start_pos, old_editable->selection_end_pos);
5360   end2 = MAX(old_editable->selection_start_pos, old_editable->selection_end_pos);
5361   
5362   if (start2 < start1)
5363     {
5364       guint tmp;
5365       
5366       tmp = start1; start1 = start2; start2 = tmp;
5367       tmp = end1;   end1   = end2;   end2   = tmp;
5368     }
5369   
5370   undraw_cursor (text, FALSE);
5371   old_editable->selection_start_pos = start;
5372   old_editable->selection_end_pos = end;
5373   draw_cursor (text, FALSE);
5374   
5375   /* Expose only what changed */
5376   
5377   if (start1 < start2)
5378     gtk_text_update_text (old_editable, start1, MIN(end1, start2));
5379   
5380   if (end2 > end1)
5381     gtk_text_update_text (old_editable, MAX(end1, start2), end2);
5382   else if (end2 < end1)
5383     gtk_text_update_text (old_editable, end2, end1);
5384 }
5385
5386
5387 /**********************************************************************/
5388 /*                              Debug                                 */
5389 /**********************************************************************/
5390
5391 #ifdef DEBUG_GTK_TEXT
5392 static void
5393 gtk_text_show_cache_line (GtkText *text, GList *cache,
5394                           const char* what, const char* func, gint line)
5395 {
5396   LineParams *lp = &CACHE_DATA(cache);
5397   gint i;
5398   
5399   if (cache == text->line_start_cache)
5400     g_message ("Line Start Cache: ");
5401   
5402   if (cache == text->current_line)
5403     g_message("Current Line: ");
5404   
5405   g_message ("%s:%d: cache line %s s=%d,e=%d,lh=%d (",
5406              func,
5407              line,
5408              what,
5409              lp->start.index,
5410              lp->end.index,
5411              LINE_HEIGHT(*lp));
5412   
5413   for (i = lp->start.index; i < (lp->end.index + lp->wraps); i += 1)
5414     g_message ("%c", GTK_TEXT_INDEX (text, i));
5415   
5416   g_message (")\n");
5417 }
5418
5419 static void
5420 gtk_text_show_cache (GtkText *text, const char* func, gint line)
5421 {
5422   GList *l = text->line_start_cache;
5423   
5424   if (!l) {
5425     return;
5426   }
5427   
5428   /* back up to the absolute beginning of the line cache */
5429   while (l->prev)
5430     l = l->prev;
5431   
5432   g_message ("*** line cache ***\n");
5433   for (; l; l = l->next)
5434     gtk_text_show_cache_line (text, l, "all", func, line);
5435 }
5436
5437 static void
5438 gtk_text_assert_mark (GtkText         *text,
5439                       GtkPropertyMark *mark,
5440                       GtkPropertyMark *before,
5441                       GtkPropertyMark *after,
5442                       const gchar     *msg,
5443                       const gchar     *where,
5444                       gint             line)
5445 {
5446   GtkPropertyMark correct_mark = find_mark (text, mark->index);
5447   
5448   if (mark->offset != correct_mark.offset ||
5449       mark->property != correct_mark.property)
5450     g_warning ("incorrect %s text property marker in %s:%d, index %d -- bad!", where, msg, line, mark->index);
5451 }
5452
5453 static void
5454 gtk_text_assert (GtkText         *text,
5455                  const gchar     *msg,
5456                  gint             line)
5457 {
5458   GList* cache = text->line_start_cache;
5459   GtkPropertyMark* before_mark = NULL;
5460   GtkPropertyMark* after_mark = NULL;
5461   
5462   gtk_text_show_props (text, msg, line);
5463   
5464   for (; cache->prev; cache = cache->prev)
5465     /* nothing */;
5466   
5467   g_message ("*** line markers ***\n");
5468   
5469   for (; cache; cache = cache->next)
5470     {
5471       after_mark = &CACHE_DATA(cache).end;
5472       gtk_text_assert_mark (text, &CACHE_DATA(cache).start, before_mark, after_mark, msg, "start", line);
5473       before_mark = &CACHE_DATA(cache).start;
5474       
5475       if (cache->next)
5476         after_mark = &CACHE_DATA(cache->next).start;
5477       else
5478         after_mark = NULL;
5479       
5480       gtk_text_assert_mark (text, &CACHE_DATA(cache).end, before_mark, after_mark, msg, "end", line);
5481       before_mark = &CACHE_DATA(cache).end;
5482     }
5483 }
5484
5485 static void
5486 gtk_text_show_adj (GtkText *text,
5487                    GtkAdjustment *adj,
5488                    const char* what,
5489                    const char* func,
5490                    gint line)
5491 {
5492   g_message ("*** adjustment ***\n");
5493   
5494   g_message ("%s:%d: %s adjustment l=%.1f u=%.1f v=%.1f si=%.1f pi=%.1f ps=%.1f\n",
5495              func,
5496              line,
5497              what,
5498              adj->lower,
5499              adj->upper,
5500              adj->value,
5501              adj->step_increment,
5502              adj->page_increment,
5503              adj->page_size);
5504 }
5505
5506 static void
5507 gtk_text_show_props (GtkText *text,
5508                      const char* msg,
5509                      int line)
5510 {
5511   GList* props = text->text_properties;
5512   int proplen = 0;
5513   
5514   g_message ("%s:%d: ", msg, line);
5515   
5516   for (; props; props = props->next)
5517     {
5518       TextProperty *p = (TextProperty*)props->data;
5519       
5520       proplen += p->length;
5521
5522       g_message ("[%d,%p,", p->length, p);
5523       if (p->flags & PROPERTY_FONT)
5524         g_message ("%p,", p->font);
5525       else
5526         g_message ("-,");
5527       if (p->flags & PROPERTY_FOREGROUND)
5528         g_message ("%ld, ", p->fore_color.pixel);
5529       else
5530         g_message ("-,");
5531       if (p->flags & PROPERTY_BACKGROUND)
5532         g_message ("%ld] ", p->back_color.pixel);
5533       else
5534         g_message ("-] ");
5535     }
5536   
5537   g_message ("\n");
5538   
5539   if (proplen - 1 != TEXT_LENGTH(text))
5540     g_warning ("incorrect property list length in %s:%d -- bad!", msg, line);
5541 }
5542 #endif