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