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