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