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