gtkstext widget (replacing gtktext with more mail friendly editor)
[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                 data->found = TRUE;
4219                 return TRUE;
4220         }
4221         else {
4222                 data->lp = *params;
4223                 return FALSE;
4224         }
4225 }
4226
4227 static void move_cursor_to_display_row_up(GtkSText *text)
4228 {
4229         LineParams    lp;
4230         bdrf              data = { 0 };
4231         int                       new_index;
4232         int                   col;
4233         GtkSPropertyMark  mark = find_this_line_start_mark(text, text->cursor_mark.index, &text->cursor_mark);
4234
4235         /* top of buffer */
4236         if (mark.index == 0) {
4237                 return;
4238         }
4239
4240         /* we need to previous DISPLAY row not the previous BUFFER line, so we go one line back,
4241          * and iterate over the lines until we have a LineParams that matches the original */
4242
4243         lp  = CACHE_DATA(text->current_line);
4244         col = (text->cursor_mark.index - lp.start.index);
4245         data.start = lp.start.index;
4246         data.end   = lp.end.index;
4247
4248         /* get the previous line */
4249         if (mark.index - 1 > 0) {
4250                 decrement_mark(&mark);
4251                 if (mark.index - 1 > 0) {
4252                         mark = find_this_line_start_mark(text, mark.index -1,  &mark);
4253                 }                       
4254         }               
4255         
4256         /* let's get the previous display line */
4257         line_params_iterate(text, &mark, NULL, FALSE, &data, 
4258                                                 (LineIteratorFunction)back_display_row_fetcher);        
4259                 
4260         if (data.found) {
4261                 if (col < text->persist_column) col = text->persist_column; 
4262                 else text->persist_column = col;
4263                 new_index = data.lp.start.index + col;
4264                 if (new_index > data.lp.end.index) {
4265                         new_index = data.lp.end.index;
4266                 }
4267                 /* and move the cursor */
4268                 gtk_stext_set_position_X(GTK_EDITABLE(text), new_index);                
4269         }
4270 }
4271
4272 typedef struct {
4273         gboolean         found;
4274         gboolean         completed;
4275         gint             start, end;
4276         LineParams   lp;
4277 } fdrf; 
4278
4279 static gint forward_display_row_fetcher(GtkSText *text,
4280                                                                                 LineParams *lp,
4281                                                                                 fdrf       *data)
4282 {
4283         if (data->found) {
4284                 data->lp = *lp;
4285                 data->completed = TRUE;
4286                 return TRUE;
4287         }
4288         else if (data->start == lp->start.index && data->end == lp->end.index) {
4289                 data->found = TRUE;
4290                 return FALSE;
4291         }
4292         else {
4293                 return FALSE;
4294         }
4295 }
4296
4297 static void move_cursor_to_display_row_down     (GtkSText *text)
4298 {
4299         LineParams              lp;
4300         int                             new_index;
4301         int                             col;
4302         GtkSPropertyMark  mark = find_this_line_start_mark(text, text->cursor_mark.index, &text->cursor_mark);
4303         fdrf                    data = { FALSE, FALSE };
4304
4305         lp  = CACHE_DATA(text->current_line);
4306         col = (text->cursor_mark.index - lp.start.index);
4307
4308         data.start = lp.start.index;
4309         data.end   = lp.end.index;
4310
4311         /* find the next DISPLAY line */ 
4312         line_params_iterate(text, &mark, NULL, FALSE, &data, 
4313                                                 (LineIteratorFunction)forward_display_row_fetcher);     
4314         
4315         if (data.completed) {
4316                 if (col < text->persist_column) col = text->persist_column; 
4317                 else text->persist_column = col;
4318                 new_index = data.lp.start.index + col;
4319                 if (new_index > data.lp.end.index) {
4320                         new_index = data.lp.end.index;
4321                 }
4322                 /* and move the cursor */
4323                 gtk_stext_set_position_X(GTK_EDITABLE(text), new_index);                
4324         }
4325 }
4326
4327 static void reset_persist_col_pos(GtkSText *text)
4328 {
4329         text->persist_column = 0;
4330 }
4331
4332 static void 
4333 gtk_stext_move_cursor (GtkEditable *editable,
4334                       gint         x,
4335                       gint         y)
4336 {
4337   if (x > 0)
4338     {
4339       while (x-- != 0)
4340         move_cursor_hor (GTK_STEXT (editable), 1);
4341     }
4342   else if (x < 0)
4343     {
4344       while (x++ != 0)
4345         move_cursor_hor (GTK_STEXT (editable), -1);
4346     }
4347   
4348   if (y > 0)
4349     {
4350       while (y-- != 0)
4351         move_cursor_ver (GTK_STEXT (editable), 1);
4352     }
4353   else if (y < 0)
4354     {
4355       while (y++ != 0)
4356         move_cursor_ver (GTK_STEXT (editable), -1);
4357     }
4358 }
4359
4360 static void
4361 gtk_stext_move_forward_character (GtkSText *text)
4362 {
4363   move_cursor_hor (text, 1);
4364 }
4365
4366 static void
4367 gtk_stext_move_backward_character (GtkSText *text)
4368 {
4369   move_cursor_hor (text, -1);
4370 }
4371
4372 static void
4373 gtk_stext_move_next_line (GtkSText *text)
4374 {
4375   move_cursor_ver (text, 1);
4376 }
4377
4378 static void
4379 gtk_stext_move_previous_line (GtkSText *text)
4380 {
4381   move_cursor_ver (text, -1);
4382 }
4383
4384 static void 
4385 gtk_stext_move_word (GtkEditable *editable,
4386                     gint         n)
4387 {
4388   if (n > 0)
4389     {
4390       while (n-- != 0)
4391         gtk_stext_move_forward_word (GTK_STEXT (editable));
4392     }
4393   else if (n < 0)
4394     {
4395       while (n++ != 0)
4396         gtk_stext_move_backward_word (GTK_STEXT (editable));
4397     }
4398 }
4399
4400 static void
4401 gtk_stext_move_forward_word (GtkSText *text)
4402 {
4403   text->cursor_virtual_x = 0;
4404   
4405   undraw_cursor (text, FALSE);
4406   
4407   if (text->use_wchar)
4408     {
4409       while (!LAST_INDEX (text, text->cursor_mark) && 
4410              !gdk_iswalnum (GTK_STEXT_INDEX(text, text->cursor_mark.index)))
4411         advance_mark (&text->cursor_mark);
4412       
4413       while (!LAST_INDEX (text, text->cursor_mark) && 
4414              gdk_iswalnum (GTK_STEXT_INDEX(text, text->cursor_mark.index)))
4415         advance_mark (&text->cursor_mark);
4416     }
4417   else
4418     {
4419       while (!LAST_INDEX (text, text->cursor_mark) && 
4420              !isalnum (GTK_STEXT_INDEX(text, text->cursor_mark.index)))
4421         advance_mark (&text->cursor_mark);
4422       
4423       while (!LAST_INDEX (text, text->cursor_mark) && 
4424              isalnum (GTK_STEXT_INDEX(text, text->cursor_mark.index)))
4425         advance_mark (&text->cursor_mark);
4426     }
4427   
4428   find_cursor (text, TRUE);
4429   draw_cursor (text, FALSE);
4430 }
4431
4432 static void
4433 gtk_stext_move_backward_word (GtkSText *text)
4434 {
4435   text->cursor_virtual_x = 0;
4436   
4437   undraw_cursor (text, FALSE);
4438   
4439   if (text->use_wchar)
4440     {
4441       while ((text->cursor_mark.index > 0) &&
4442              !gdk_iswalnum (GTK_STEXT_INDEX(text, text->cursor_mark.index-1)))
4443         decrement_mark (&text->cursor_mark);
4444       
4445       while ((text->cursor_mark.index > 0) &&
4446              gdk_iswalnum (GTK_STEXT_INDEX(text, text->cursor_mark.index-1)))
4447         decrement_mark (&text->cursor_mark);
4448     }
4449   else
4450     {
4451       while ((text->cursor_mark.index > 0) &&
4452              !isalnum (GTK_STEXT_INDEX(text, text->cursor_mark.index-1)))
4453         decrement_mark (&text->cursor_mark);
4454       
4455       while ((text->cursor_mark.index > 0) &&
4456              isalnum (GTK_STEXT_INDEX(text, text->cursor_mark.index-1)))
4457         decrement_mark (&text->cursor_mark);
4458     }
4459   
4460   find_cursor (text, TRUE);
4461   draw_cursor (text, FALSE);
4462 }
4463
4464 static void 
4465 gtk_stext_move_page (GtkEditable *editable,
4466                     gint         x,
4467                     gint         y)
4468 {
4469   if (y != 0)
4470     scroll_int (GTK_STEXT (editable), 
4471                 y * GTK_STEXT(editable)->vadj->page_increment);  
4472 }
4473
4474 static void 
4475 gtk_stext_move_to_row (GtkEditable *editable,
4476                       gint         row)
4477 {
4478 }
4479
4480 static void 
4481 gtk_stext_move_to_column (GtkEditable *editable,
4482                          gint         column)
4483 {
4484   GtkSText *text;
4485   
4486   text = GTK_STEXT (editable);
4487   
4488   text->cursor_virtual_x = 0;   /* FIXME */
4489   
4490   undraw_cursor (text, FALSE);
4491   
4492   /* Move to the beginning of the line */
4493   while ((text->cursor_mark.index > 0) &&
4494          (GTK_STEXT_INDEX (text, text->cursor_mark.index - 1) != LINE_DELIM))
4495     decrement_mark (&text->cursor_mark);
4496   
4497   while (!LAST_INDEX (text, text->cursor_mark) &&
4498          (GTK_STEXT_INDEX (text, text->cursor_mark.index) != LINE_DELIM))
4499     {
4500       if (column > 0)
4501         column--;
4502       else if (column == 0)
4503         break;
4504       
4505       advance_mark (&text->cursor_mark);
4506     }
4507   
4508   find_cursor (text, TRUE);
4509   draw_cursor (text, FALSE);
4510 }
4511
4512 static void
4513 gtk_stext_move_beginning_of_line (GtkSText *text)
4514 {
4515   gtk_stext_move_to_column (GTK_EDITABLE (text), 0);
4516   
4517 }
4518
4519 static void
4520 gtk_stext_move_end_of_line (GtkSText *text)
4521 {
4522   gtk_stext_move_to_column (GTK_EDITABLE (text), -1);
4523 }
4524
4525 static void 
4526 gtk_stext_kill_char (GtkEditable *editable,
4527                     gint         direction)
4528 {
4529   GtkSText *text;
4530   
4531   text = GTK_STEXT (editable);
4532   
4533   if (editable->selection_start_pos != editable->selection_end_pos)
4534     gtk_editable_delete_selection (editable);
4535   else
4536     {
4537       if (direction >= 0)
4538         {
4539           if (text->point.index + 1 <= TEXT_LENGTH (text))
4540             gtk_editable_delete_text (editable, text->point.index, text->point.index + 1);
4541         }
4542       else
4543         {
4544           if (text->point.index > 0)
4545             gtk_editable_delete_text (editable, text->point.index - 1, text->point.index);
4546         }
4547     }
4548 }
4549
4550 static void
4551 gtk_stext_delete_forward_character (GtkSText *text)
4552 {
4553   gtk_stext_kill_char (GTK_EDITABLE (text), 1);
4554 }
4555
4556 static void
4557 gtk_stext_delete_backward_character (GtkSText *text)
4558 {
4559   gtk_stext_kill_char (GTK_EDITABLE (text), -1);
4560 }
4561
4562 static void 
4563 gtk_stext_kill_word (GtkEditable *editable,
4564                     gint         direction)
4565 {
4566   if (editable->selection_start_pos != editable->selection_end_pos)
4567     gtk_editable_delete_selection (editable);
4568   else
4569     {
4570       gint old_pos = editable->current_pos;
4571       if (direction >= 0)
4572         {
4573           gtk_stext_move_word (editable, 1);
4574           gtk_editable_delete_text (editable, old_pos, editable->current_pos);
4575         }
4576       else
4577         {
4578           gtk_stext_move_word (editable, -1);
4579           gtk_editable_delete_text (editable, editable->current_pos, old_pos);
4580         }
4581     }
4582 }
4583
4584 static void
4585 gtk_stext_delete_forward_word (GtkSText *text)
4586 {
4587   gtk_stext_kill_word (GTK_EDITABLE (text), 1);
4588 }
4589
4590 static void
4591 gtk_stext_delete_backward_word (GtkSText *text)
4592 {
4593   gtk_stext_kill_word (GTK_EDITABLE (text), -1);
4594 }
4595
4596 static void 
4597 gtk_stext_kill_line (GtkEditable *editable,
4598                     gint         direction)
4599 {
4600   gint old_pos = editable->current_pos;
4601   if (direction >= 0)
4602     {
4603       gtk_stext_move_to_column (editable, -1);
4604       gtk_editable_delete_text (editable, old_pos, editable->current_pos);
4605     }
4606   else
4607     {
4608       gtk_stext_move_to_column (editable, 0);
4609       gtk_editable_delete_text (editable, editable->current_pos, old_pos);
4610     }
4611 }
4612
4613 static void
4614 gtk_stext_delete_line (GtkSText *text)
4615 {
4616   gtk_stext_move_to_column (GTK_EDITABLE (text), 0);
4617   gtk_stext_kill_line (GTK_EDITABLE (text), 1);
4618 }
4619
4620 static void
4621 gtk_stext_delete_to_line_end (GtkSText *text)
4622 {
4623   gtk_stext_kill_line (GTK_EDITABLE (text), 1);
4624 }
4625
4626 static void
4627 gtk_stext_select_word (GtkSText *text, guint32 time)
4628 {
4629   gint start_pos;
4630   gint end_pos;
4631   
4632   GtkEditable *editable;
4633   editable = GTK_EDITABLE (text);
4634   
4635   gtk_stext_move_backward_word (text);
4636   start_pos = text->cursor_mark.index;
4637   
4638   gtk_stext_move_forward_word (text);
4639   end_pos = text->cursor_mark.index;
4640   
4641   editable->has_selection = TRUE;
4642   gtk_stext_set_selection (editable, start_pos, end_pos);
4643   gtk_editable_claim_selection (editable, start_pos != end_pos, time);
4644 }
4645
4646 static void
4647 gtk_stext_select_line (GtkSText *text, guint32 time)
4648 {
4649   gint start_pos;
4650   gint end_pos;
4651   
4652   GtkEditable *editable;
4653   editable = GTK_EDITABLE (text);
4654   
4655   gtk_stext_move_beginning_of_line (text);
4656   start_pos = text->cursor_mark.index;
4657   
4658   gtk_stext_move_end_of_line (text);
4659   gtk_stext_move_forward_character (text);
4660   end_pos = text->cursor_mark.index;
4661   
4662   editable->has_selection = TRUE;
4663   gtk_stext_set_selection (editable, start_pos, end_pos);
4664   gtk_editable_claim_selection (editable, start_pos != end_pos, time);
4665 }
4666
4667 /**********************************************************************/
4668 /*                            Scrolling                               */
4669 /**********************************************************************/
4670
4671 static void
4672 adjust_adj (GtkSText* text, GtkAdjustment* adj)
4673 {
4674   gint height;
4675   
4676   gdk_window_get_size (text->text_area, NULL, &height);
4677   
4678   adj->step_increment = MIN (adj->upper, (float) SCROLL_PIXELS);
4679   adj->page_increment = MIN (adj->upper, height - (float) KEY_SCROLL_PIXELS);
4680   adj->page_size      = MIN (adj->upper, height);
4681   adj->value          = MIN (adj->value, adj->upper - adj->page_size);
4682   adj->value          = MAX (adj->value, 0.0);
4683   
4684   gtk_signal_emit_by_name (GTK_OBJECT (adj), "changed");
4685 }
4686
4687 static gint
4688 set_vertical_scroll_iterator (GtkSText* text, LineParams* lp, void* data)
4689 {
4690   SetVerticalScrollData *svdata = (SetVerticalScrollData *) data;
4691   
4692   if ((text->first_line_start_index >= lp->start.index) &&
4693       (text->first_line_start_index <= lp->end.index))
4694     {
4695       svdata->mark = lp->start;
4696   
4697       if (text->first_line_start_index == lp->start.index)
4698         {
4699           text->first_onscreen_ver_pixel = svdata->pixel_height + text->first_cut_pixels;
4700         }
4701       else
4702         {
4703           text->first_onscreen_ver_pixel = svdata->pixel_height;
4704           text->first_cut_pixels = 0;
4705         }
4706       
4707       text->vadj->value = (float) text->first_onscreen_ver_pixel;
4708     }
4709   
4710   svdata->pixel_height += LINE_HEIGHT (*lp);
4711   
4712   return FALSE;
4713 }
4714
4715 static gint
4716 set_vertical_scroll_find_iterator (GtkSText* text, LineParams* lp, void* data)
4717 {
4718   SetVerticalScrollData *svdata = (SetVerticalScrollData *) data;
4719   gint return_val;
4720   
4721   if (svdata->pixel_height <= (gint) text->vadj->value &&
4722       svdata->pixel_height + LINE_HEIGHT(*lp) > (gint) text->vadj->value)
4723     {
4724       svdata->mark = lp->start;
4725       
4726       text->first_cut_pixels = (gint)text->vadj->value - svdata->pixel_height;
4727       text->first_onscreen_ver_pixel = svdata->pixel_height;
4728       text->first_line_start_index = lp->start.index;
4729       
4730       return_val = TRUE;
4731     }
4732   else
4733     {
4734       svdata->pixel_height += LINE_HEIGHT (*lp);
4735       
4736       return_val = FALSE;
4737     }
4738   
4739   return return_val;
4740 }
4741
4742 static GtkSPropertyMark
4743 set_vertical_scroll (GtkSText* text)
4744 {
4745   GtkSPropertyMark mark = find_mark (text, 0);
4746   SetVerticalScrollData data;
4747   gint height;
4748   gint orig_value;
4749   
4750   data.pixel_height = 0;
4751   line_params_iterate (text, &mark, NULL, FALSE, &data, set_vertical_scroll_iterator);
4752   
4753   text->vadj->upper = (float) data.pixel_height;
4754   orig_value = (gint) text->vadj->value;
4755   
4756   gdk_window_get_size (text->text_area, NULL, &height);
4757   
4758   text->vadj->step_increment = MIN (text->vadj->upper, (float) SCROLL_PIXELS);
4759   text->vadj->page_increment = MIN (text->vadj->upper, height - (float) KEY_SCROLL_PIXELS);
4760   text->vadj->page_size      = MIN (text->vadj->upper, height);
4761   text->vadj->value          = MIN (text->vadj->value, text->vadj->upper - text->vadj->page_size);
4762   text->vadj->value          = MAX (text->vadj->value, 0.0);
4763   
4764   text->last_ver_value = (gint)text->vadj->value;
4765   
4766   gtk_signal_emit_by_name (GTK_OBJECT (text->vadj), "changed");
4767   
4768   if (text->vadj->value != orig_value)
4769     {
4770       /* We got clipped, and don't really know which line to put first. */
4771       data.pixel_height = 0;
4772       data.last_didnt_wrap = TRUE;
4773       
4774       line_params_iterate (text, &mark, NULL,
4775                            FALSE, &data,
4776                            set_vertical_scroll_find_iterator);
4777     }
4778
4779   return data.mark;
4780 }
4781
4782 static void
4783 scroll_int (GtkSText* text, gint diff)
4784 {
4785   gfloat upper;
4786   
4787   text->vadj->value += diff;
4788   
4789   upper = text->vadj->upper - text->vadj->page_size;
4790   text->vadj->value = MIN (text->vadj->value, upper);
4791   text->vadj->value = MAX (text->vadj->value, 0.0);
4792   
4793   gtk_signal_emit_by_name (GTK_OBJECT (text->vadj), "value_changed");
4794 }
4795
4796 static void 
4797 process_exposes (GtkSText *text)
4798 {
4799   GdkEvent *event;
4800   
4801   /* Make sure graphics expose events are processed before scrolling
4802    * again */
4803   
4804   while ((event = gdk_event_get_graphics_expose (text->text_area)) != NULL)
4805     {
4806       gtk_widget_event (GTK_WIDGET (text), event);
4807       if (event->expose.count == 0)
4808         {
4809           gdk_event_free (event);
4810           break;
4811         }
4812       gdk_event_free (event);
4813     }
4814 }
4815
4816 static gint last_visible_line_height (GtkSText* text)
4817 {
4818   GList *cache = text->line_start_cache;
4819   gint height;
4820   
4821   gdk_window_get_size (text->text_area, NULL, &height);
4822   
4823   for (; cache->next; cache = cache->next)
4824     if (pixel_height_of(text, cache->next) > height)
4825       break;
4826   
4827   if (cache)
4828     return pixel_height_of(text, cache) - 1;
4829   else
4830     return 0;
4831 }
4832
4833 static gint first_visible_line_height (GtkSText* text)
4834 {
4835   if (text->first_cut_pixels)
4836     return pixel_height_of(text, text->line_start_cache) + 1;
4837   else
4838     return 1;
4839 }
4840
4841 static void
4842 scroll_down (GtkSText* text, gint diff0)
4843 {
4844   GdkRectangle rect;
4845   gint real_diff = 0;
4846   gint width, height;
4847   
4848   text->first_onscreen_ver_pixel += diff0;
4849   
4850   while (diff0-- > 0)
4851     {
4852       if (text->first_cut_pixels < LINE_HEIGHT(CACHE_DATA(text->line_start_cache)) - 1)
4853         {
4854           text->first_cut_pixels += 1;
4855         }
4856       else
4857         {
4858           text->first_cut_pixels = 0;
4859           
4860           text->line_start_cache = text->line_start_cache->next;
4861           g_assert (text->line_start_cache);
4862       
4863           text->first_line_start_index =
4864             CACHE_DATA(text->line_start_cache).start.index;
4865           
4866           if (!text->line_start_cache->next)
4867             fetch_lines_forward (text, 1);
4868         }
4869       
4870       real_diff += 1;
4871     }
4872   
4873   gdk_window_get_size (text->text_area, &width, &height);
4874   if (height > real_diff)
4875     gdk_draw_pixmap (text->text_area,
4876                      text->gc,
4877                      text->text_area,
4878                      0,
4879                      real_diff,
4880                      0,
4881                      0,
4882                      width,
4883                      height - real_diff);
4884   
4885   rect.x      = 0;
4886   rect.y      = MAX (0, height - real_diff);
4887   rect.width  = width;
4888   rect.height = MIN (height, real_diff);
4889   
4890   expose_text (text, &rect, FALSE);
4891   gtk_stext_draw_focus ( (GtkWidget *) text);
4892   
4893   if (text->current_line)
4894     {
4895       gint cursor_min;
4896       
4897       text->cursor_pos_y -= real_diff;
4898       cursor_min = drawn_cursor_min(text);
4899       
4900       if (cursor_min < 0)
4901         find_mouse_cursor (text, text->cursor_pos_x,
4902                            first_visible_line_height (text));
4903     }
4904   
4905   if (height > real_diff)
4906     process_exposes (text);
4907 }
4908
4909 static void
4910 scroll_up (GtkSText* text, gint diff0)
4911 {
4912   gint real_diff = 0;
4913   GdkRectangle rect;
4914   gint width, height;
4915   
4916   text->first_onscreen_ver_pixel += diff0;
4917   
4918   while (diff0++ < 0)
4919     {
4920       g_assert (text->line_start_cache);
4921       
4922       if (text->first_cut_pixels > 0)
4923         {
4924           text->first_cut_pixels -= 1;
4925         }
4926       else
4927         {
4928           if (!text->line_start_cache->prev)
4929             fetch_lines_backward (text);
4930           
4931           text->line_start_cache = text->line_start_cache->prev;
4932           
4933           text->first_line_start_index =
4934             CACHE_DATA(text->line_start_cache).start.index;
4935           
4936           text->first_cut_pixels = LINE_HEIGHT(CACHE_DATA(text->line_start_cache)) - 1;
4937         }
4938       
4939       real_diff += 1;
4940     }
4941   
4942   gdk_window_get_size (text->text_area, &width, &height);
4943   if (height > real_diff)
4944     gdk_draw_pixmap (text->text_area,
4945                      text->gc,
4946                      text->text_area,
4947                      0,
4948                      0,
4949                      0,
4950                      real_diff,
4951                      width,
4952                      height - real_diff);
4953   
4954   rect.x      = 0;
4955   rect.y      = 0;
4956   rect.width  = width;
4957   rect.height = MIN (height, real_diff);
4958   
4959   expose_text (text, &rect, FALSE);
4960   gtk_stext_draw_focus ( (GtkWidget *) text);
4961   
4962   if (text->current_line)
4963     {
4964       gint cursor_max;
4965       gint height;
4966       
4967       text->cursor_pos_y += real_diff;
4968       cursor_max = drawn_cursor_max(text);
4969       gdk_window_get_size (text->text_area, NULL, &height);
4970       
4971       if (cursor_max >= height)
4972         find_mouse_cursor (text, text->cursor_pos_x,
4973                            last_visible_line_height (text));
4974     }
4975   
4976   if (height > real_diff)
4977     process_exposes (text);
4978 }
4979
4980 /**********************************************************************/
4981 /*                            Display Code                            */
4982 /**********************************************************************/
4983
4984 /* Assumes mark starts a line.  Calculates the height, width, and
4985  * displayable character count of a single DISPLAYABLE line.  That
4986  * means that in line-wrap mode, this does may not compute the
4987  * properties of an entire line. */
4988 static LineParams
4989 find_line_params (GtkSText* text,
4990                   const GtkSPropertyMark* mark,
4991                   const PrevTabCont *tab_cont,
4992                   PrevTabCont *next_cont)
4993 {
4994   LineParams lp;
4995   TabStopMark tab_mark = tab_cont->tab_start;
4996   guint max_display_pixels;
4997   GdkWChar ch;
4998   gint ch_width;
4999   GdkFont *font;
5000   
5001   gdk_window_get_size (text->text_area, (gint*) &max_display_pixels, NULL);
5002
5003   if (text->wrap_rmargin) {
5004         /* SYLPHEED - since sylpheed is a mail program, assume we work with
5005          * fixed fonts. only assume we're using one font! */
5006         font = MARK_CURRENT_FONT(text, mark);
5007
5008         /* SYLPHEED - ok for multi byte charsets to check for ASCII char? 
5009      */
5010         if (text->use_wchar)
5011                 ch_width = gdk_char_width_wc(font, 'W');                
5012         else
5013                 ch_width = gdk_char_width(font, 'W');
5014   
5015         /* SYLPHEED - max_display_chars has the rmargin in pixels
5016          */
5017         max_display_pixels = text->wrap_rmargin * ch_width; 
5018   }     
5019   
5020   if (GTK_EDITABLE (text)->editable || !text->word_wrap)
5021     max_display_pixels -= LINE_WRAP_ROOM;
5022   
5023   lp.wraps             = 0;
5024   lp.tab_cont          = *tab_cont;
5025   lp.start             = *mark;
5026   lp.end               = *mark;
5027   lp.pixel_width       = tab_cont->pixel_offset;
5028   lp.displayable_chars = 0;
5029   lp.font_ascent       = 0;
5030   lp.font_descent      = 0;
5031   
5032   init_tab_cont (text, next_cont);
5033   
5034   while (!LAST_INDEX(text, lp.end))
5035     {
5036       g_assert (lp.end.property);
5037       
5038       ch   = GTK_STEXT_INDEX (text, lp.end.index);
5039       font = MARK_CURRENT_FONT (text, &lp.end);
5040
5041       if (ch == LINE_DELIM)
5042         {
5043           /* Newline doesn't count in computation of line height, even
5044            * if its in a bigger font than the rest of the line.  Unless,
5045            * of course, there are no other characters. */
5046           
5047           if (!lp.font_ascent && !lp.font_descent)
5048             {
5049               lp.font_ascent = font->ascent;
5050               lp.font_descent = font->descent;
5051             }
5052           
5053           lp.tab_cont_next = *next_cont;
5054           
5055           return lp;
5056         }
5057       
5058       ch_width = find_char_width (text, &lp.end, &tab_mark);
5059       
5060       if ((ch_width + lp.pixel_width > max_display_pixels) &&
5061           (lp.end.index > lp.start.index))
5062         {
5063           lp.wraps = 1;
5064           
5065           if (text->line_wrap)
5066             {
5067               next_cont->tab_start    = tab_mark;
5068               next_cont->pixel_offset = 0;
5069               
5070               if (ch == '\t')
5071                 {
5072                   /* Here's the tough case, a tab is wrapping. */
5073                   gint pixels_avail = max_display_pixels - lp.pixel_width;
5074                   gint space_width  = MARK_CURRENT_TEXT_FONT(text, &lp.end)->char_widths[' '];
5075                   gint spaces_avail = pixels_avail / space_width;
5076                   
5077                   if (spaces_avail == 0)
5078                     {
5079                       decrement_mark (&lp.end);
5080                     }
5081                   else
5082                     {
5083                       advance_tab_mark (text, &next_cont->tab_start, '\t');
5084                       next_cont->pixel_offset = space_width * (tab_mark.to_next_tab -
5085                                                                spaces_avail);
5086                       lp.displayable_chars += 1;
5087                     }
5088                 }
5089               else
5090                 {
5091                   if (text->word_wrap)
5092                     {
5093                       GtkSPropertyMark saved_mark = lp.end;
5094                       guint saved_characters = lp.displayable_chars;
5095                       
5096                       lp.displayable_chars += 1;
5097                       
5098                       if (text->use_wchar)
5099                         {
5100                           while (!gdk_iswspace (GTK_STEXT_INDEX (text, lp.end.index)) &&
5101                                  (lp.end.index > lp.start.index))
5102                             {
5103                               decrement_mark (&lp.end);
5104                               lp.displayable_chars -= 1;
5105                             }
5106                         }
5107                       else
5108                         {
5109                           while (!isspace(GTK_STEXT_INDEX (text, lp.end.index)) &&
5110                                  (lp.end.index > lp.start.index))
5111                             {
5112                               decrement_mark (&lp.end);
5113                               lp.displayable_chars -= 1;
5114                             }
5115                         }
5116                       
5117                       /* If whole line is one word, revert to char wrapping */
5118                       if (lp.end.index == lp.start.index)
5119                         {
5120                           lp.end = saved_mark;
5121                           lp.displayable_chars = saved_characters;
5122                           decrement_mark (&lp.end);
5123                         }
5124                     }
5125                   else
5126                     {
5127                       /* Don't include this character, it will wrap. */
5128                       decrement_mark (&lp.end);
5129                     }
5130                 }
5131               
5132               lp.tab_cont_next = *next_cont;
5133               
5134               return lp;
5135             }
5136         }
5137       else
5138         {
5139           lp.displayable_chars += 1;
5140         }
5141       
5142       lp.font_ascent = MAX (font->ascent, lp.font_ascent);
5143       lp.font_descent = MAX (font->descent, lp.font_descent);
5144       lp.pixel_width  += ch_width;
5145       
5146       advance_mark(&lp.end);
5147       advance_tab_mark (text, &tab_mark, ch);
5148     }
5149   
5150   if (LAST_INDEX(text, lp.start))
5151     {
5152       /* Special case, empty last line. */
5153       font = MARK_CURRENT_FONT (text, &lp.end);
5154
5155       lp.font_ascent = font->ascent;
5156       lp.font_descent = font->descent;
5157     }
5158   
5159   lp.tab_cont_next = *next_cont;
5160   
5161   return lp;
5162 }
5163
5164 static void
5165 expand_scratch_buffer (GtkSText* text, guint len)
5166 {
5167   if (len >= text->scratch_buffer_len)
5168     {
5169       guint i = 1;
5170       
5171       while (i <= len && i < MIN_GAP_SIZE) i <<= 1;
5172       
5173       if (text->use_wchar)
5174         {
5175           if (!text->scratch_buffer.wc)
5176             text->scratch_buffer.wc = g_new (GdkWChar, i);
5177           else
5178             text->scratch_buffer.wc = g_realloc (text->scratch_buffer.wc,
5179                                                  i * sizeof (GdkWChar));
5180         }
5181       else
5182         {
5183           if (!text->scratch_buffer.ch)
5184             text->scratch_buffer.ch = g_new (guchar, i);
5185           else
5186             text->scratch_buffer.ch = g_realloc (text->scratch_buffer.ch, i);
5187         }
5188       
5189       text->scratch_buffer_len = i;
5190     }
5191 }
5192
5193 /* Side effect: modifies text->gc
5194  */
5195
5196 static void
5197 draw_bg_rect (GtkSText* text, GtkSPropertyMark *mark,
5198               gint x, gint y, gint width, gint height,
5199               gboolean already_cleared)
5200 {
5201   GtkEditable *editable = GTK_EDITABLE(text);
5202
5203   if ((mark->index >= MIN(editable->selection_start_pos, editable->selection_end_pos) &&
5204        mark->index < MAX(editable->selection_start_pos, editable->selection_end_pos)))
5205     {
5206       gtk_paint_flat_box(GTK_WIDGET(text)->style, text->text_area,
5207                          editable->has_selection ?
5208                             GTK_STATE_SELECTED : GTK_STATE_ACTIVE, 
5209                          GTK_SHADOW_NONE,
5210                          NULL, GTK_WIDGET(text), "text",
5211                          x, y, width, height);
5212     }
5213   else if (!gdk_color_equal(MARK_CURRENT_BACK (text, mark),
5214                             &GTK_WIDGET(text)->style->base[GTK_WIDGET_STATE (text)]))
5215     {
5216       gdk_gc_set_foreground (text->gc, MARK_CURRENT_BACK (text, mark));
5217
5218       gdk_draw_rectangle (text->text_area,
5219                           text->gc,
5220                           TRUE, x, y, width, height);
5221     }
5222   else if (GTK_WIDGET (text)->style->bg_pixmap[GTK_STATE_NORMAL])
5223     {
5224       GdkRectangle rect;
5225       
5226       rect.x = x;
5227       rect.y = y;
5228       rect.width = width;
5229       rect.height = height;
5230       
5231       clear_area (text, &rect);
5232     }
5233   else if (!already_cleared)
5234     gdk_window_clear_area (text->text_area, x, y, width, height);
5235 }
5236
5237 static void
5238 draw_line (GtkSText* text,
5239            gint pixel_start_height,
5240            LineParams* lp)
5241 {
5242   GdkGCValues gc_values;
5243   gint i;
5244   gint len = 0;
5245   guint running_offset = lp->tab_cont.pixel_offset;
5246   union { GdkWChar *wc; guchar *ch; } buffer;
5247   GdkGC *fg_gc;
5248   
5249   GtkEditable *editable = GTK_EDITABLE(text);
5250   
5251   guint selection_start_pos = MIN (editable->selection_start_pos, editable->selection_end_pos);
5252   guint selection_end_pos = MAX (editable->selection_start_pos, editable->selection_end_pos);
5253   
5254   GtkSPropertyMark mark = lp->start;
5255   TabStopMark tab_mark = lp->tab_cont.tab_start;
5256   gint pixel_height = pixel_start_height + lp->font_ascent;
5257   guint chars = lp->displayable_chars;
5258   
5259   /* First provide a contiguous segment of memory.  This makes reading
5260    * the code below *much* easier, and only incurs the cost of copying
5261    * when the line being displayed spans the gap. */
5262   if (mark.index <= text->gap_position &&
5263       mark.index + chars > text->gap_position)
5264     {
5265       expand_scratch_buffer (text, chars);
5266       
5267       if (text->use_wchar)
5268         {
5269           for (i = 0; i < chars; i += 1)
5270             text->scratch_buffer.wc[i] = GTK_STEXT_INDEX(text, mark.index + i);
5271           buffer.wc = text->scratch_buffer.wc;
5272         }
5273       else
5274         {
5275           for (i = 0; i < chars; i += 1)
5276             text->scratch_buffer.ch[i] = GTK_STEXT_INDEX(text, mark.index + i);
5277           buffer.ch = text->scratch_buffer.ch;
5278         }
5279     }
5280   else
5281     {
5282       if (text->use_wchar)
5283         {
5284           if (mark.index >= text->gap_position)
5285             buffer.wc = text->text.wc + mark.index + text->gap_size;
5286           else
5287             buffer.wc = text->text.wc + mark.index;
5288         }
5289       else
5290         {
5291           if (mark.index >= text->gap_position)
5292             buffer.ch = text->text.ch + mark.index + text->gap_size;
5293           else
5294             buffer.ch = text->text.ch + mark.index;
5295         }
5296     }
5297   
5298   
5299   if (running_offset > 0)
5300     {
5301       draw_bg_rect (text, &mark, 0, pixel_start_height, running_offset,
5302                     LINE_HEIGHT (*lp), TRUE);
5303     }
5304   
5305   while (chars > 0)
5306     {
5307       len = 0;
5308       if ((text->use_wchar && buffer.wc[0] != '\t') ||
5309           (!text->use_wchar && buffer.ch[0] != '\t'))
5310         {
5311           union { GdkWChar *wc; guchar *ch; } next_tab;
5312           gint pixel_width;
5313           GdkFont *font;
5314
5315           next_tab.wc = NULL;
5316           if (text->use_wchar)
5317             for (i=0; i<chars; i++)
5318               {
5319                 if (buffer.wc[i] == '\t')
5320                   {
5321                     next_tab.wc = buffer.wc + i;
5322                     break;
5323                   }
5324               }
5325           else
5326             next_tab.ch = memchr (buffer.ch, '\t', chars);
5327
5328           len = MIN (MARK_CURRENT_PROPERTY (&mark)->length - mark.offset, chars);
5329           
5330           if (text->use_wchar)
5331             {
5332               if (next_tab.wc)
5333                 len = MIN (len, next_tab.wc - buffer.wc);
5334             }
5335           else
5336             {
5337               if (next_tab.ch)
5338                 len = MIN (len, next_tab.ch - buffer.ch);
5339             }
5340
5341           if (mark.index < selection_start_pos)
5342             len = MIN (len, selection_start_pos - mark.index);
5343           else if (mark.index < selection_end_pos)
5344             len = MIN (len, selection_end_pos - mark.index);
5345
5346           font = MARK_CURRENT_FONT (text, &mark);
5347           if (font->type == GDK_FONT_FONT)
5348             {
5349               gdk_gc_set_font (text->gc, font);
5350               gdk_gc_get_values (text->gc, &gc_values);
5351               if (text->use_wchar)
5352                 pixel_width = gdk_text_width_wc (gc_values.font,
5353                                                  buffer.wc, len);
5354               else
5355               pixel_width = gdk_text_width (gc_values.font,
5356                                               buffer.ch, len);
5357             }
5358           else
5359             {
5360               if (text->use_wchar)
5361                 pixel_width = gdk_text_width_wc (font, buffer.wc, len);
5362               else
5363                 pixel_width = gdk_text_width (font, buffer.ch, len);
5364             }
5365           
5366           draw_bg_rect (text, &mark, running_offset, pixel_start_height,
5367                         pixel_width, LINE_HEIGHT (*lp), TRUE);
5368           
5369           if ((mark.index >= selection_start_pos) && 
5370               (mark.index < selection_end_pos))
5371             {
5372               if (editable->has_selection)
5373                 fg_gc = GTK_WIDGET(text)->style->fg_gc[GTK_STATE_SELECTED];
5374               else
5375                 fg_gc = GTK_WIDGET(text)->style->fg_gc[GTK_STATE_ACTIVE];
5376             }
5377           else
5378             {
5379               gdk_gc_set_foreground (text->gc, MARK_CURRENT_FORE (text, &mark));
5380               fg_gc = text->gc;
5381             }
5382
5383           if (text->use_wchar)
5384             gdk_draw_text_wc (text->text_area, MARK_CURRENT_FONT (text, &mark),
5385                               fg_gc,
5386                               running_offset,
5387                               pixel_height,
5388                               buffer.wc,
5389                               len);
5390           else
5391             gdk_draw_text (text->text_area, MARK_CURRENT_FONT (text, &mark),
5392                            fg_gc,
5393                            running_offset,
5394                            pixel_height,
5395                            buffer.ch,
5396                            len);
5397           
5398           running_offset += pixel_width;
5399           
5400           advance_tab_mark_n (text, &tab_mark, len);
5401         }
5402       else
5403         {
5404           gint pixels_remaining;
5405           gint space_width;
5406           gint spaces_avail;
5407               
5408           len = 1;
5409           
5410           gdk_window_get_size (text->text_area, &pixels_remaining, NULL);
5411           if (GTK_EDITABLE (text)->editable || !text->word_wrap)
5412             pixels_remaining -= (LINE_WRAP_ROOM + running_offset);
5413           else
5414             pixels_remaining -= running_offset;
5415           
5416           space_width = MARK_CURRENT_TEXT_FONT(text, &mark)->char_widths[' '];
5417           
5418           spaces_avail = pixels_remaining / space_width;
5419           spaces_avail = MIN (spaces_avail, tab_mark.to_next_tab);
5420
5421           draw_bg_rect (text, &mark, running_offset, pixel_start_height,
5422                         spaces_avail * space_width, LINE_HEIGHT (*lp), TRUE);
5423
5424           running_offset += tab_mark.to_next_tab *
5425             MARK_CURRENT_TEXT_FONT(text, &mark)->char_widths[' '];
5426
5427           advance_tab_mark (text, &tab_mark, '\t');
5428         }
5429       
5430       advance_mark_n (&mark, len);
5431       if (text->use_wchar)
5432         buffer.wc += len;
5433       else
5434         buffer.ch += len;
5435       chars -= len;
5436     }
5437 }
5438
5439 static void
5440 draw_line_wrap (GtkSText* text, guint height /* baseline height */)
5441 {
5442   gint width;
5443   GdkPixmap *bitmap;
5444   gint bitmap_width;
5445   gint bitmap_height;
5446
5447   if (!GTK_EDITABLE (text)->editable && text->word_wrap)
5448     return;
5449
5450   /* SYLPHEED - don't draw ugly word wrapping thing if
5451    * our wrap margin is set */
5452   if (text->wrap_rmargin > 0) {
5453          return;
5454   }
5455   
5456   if (text->line_wrap)
5457     {
5458       bitmap = text->line_wrap_bitmap;
5459       bitmap_width = line_wrap_width;
5460       bitmap_height = line_wrap_height;
5461     }
5462   else
5463     {
5464       bitmap = text->line_arrow_bitmap;
5465       bitmap_width = line_arrow_width;
5466       bitmap_height = line_arrow_height;
5467     }
5468   
5469   gdk_window_get_size (text->text_area, &width, NULL);
5470   width -= LINE_WRAP_ROOM;
5471   
5472   gdk_gc_set_stipple (text->gc,
5473                       bitmap);
5474   
5475   gdk_gc_set_fill (text->gc, GDK_STIPPLED);
5476   
5477   gdk_gc_set_foreground (text->gc, &GTK_WIDGET (text)->style->text[GTK_STATE_NORMAL]);
5478   
5479   gdk_gc_set_ts_origin (text->gc,
5480                         width + 1,
5481                         height - bitmap_height - 1);
5482   
5483   gdk_draw_rectangle (text->text_area,
5484                       text->gc,
5485                       TRUE,
5486                       width + 1,
5487                       height - bitmap_height - 1 /* one pixel above the baseline. */,
5488                       bitmap_width,
5489                       bitmap_height);
5490   
5491   gdk_gc_set_ts_origin (text->gc, 0, 0);
5492   
5493   gdk_gc_set_fill (text->gc, GDK_SOLID);
5494 }
5495
5496 static void
5497 undraw_cursor (GtkSText* text, gint absolute)
5498 {
5499   GtkEditable *editable = (GtkEditable *)text;
5500
5501   TDEBUG (("in undraw_cursor\n"));
5502   
5503   if (absolute)
5504     text->cursor_drawn_level = 0;
5505   
5506   if ((text->cursor_drawn_level ++ == 0) &&
5507       (editable->selection_start_pos == editable->selection_end_pos) &&
5508       GTK_WIDGET_DRAWABLE (text) && text->line_start_cache)
5509     {
5510       GdkFont* font;
5511           gint pixel_width, pixel_height;
5512           GdkGC *gc;
5513       
5514       g_assert(text->cursor_mark.property);
5515
5516           gc = gdk_gc_new(text->text_area);
5517           g_assert(gc);
5518           gdk_gc_copy(gc, text->gc);
5519
5520       font = MARK_CURRENT_FONT(text, &text->cursor_mark);
5521
5522           /* SYLPHEED:
5523            * changed the cursor to a real block (TM)
5524            */
5525           if (text->cursor_type == STEXT_CURSOR_BLOCK) { 
5526                   if (text->use_wchar)
5527                         pixel_width = gdk_char_width_wc(font, text->cursor_char);               
5528                   else
5529                         pixel_width = gdk_char_width(font, text->cursor_char);
5530                   pixel_width -= 1;
5531                   pixel_height = LINE_HEIGHT(CACHE_DATA(text->current_line));
5532
5533                   draw_bg_rect (text, &text->cursor_mark,
5534                                                 text->cursor_pos_x,
5535                                                 text->cursor_pos_y - (pixel_height + 1),
5536                                                 pixel_width + 1, 
5537                                                 pixel_height + 1,
5538                                                 FALSE);
5539          }      
5540          else {
5541               draw_bg_rect (text, &text->cursor_mark,
5542                                 text->cursor_pos_x - 1,
5543                                             text->cursor_pos_y - text->cursor_char_offset - font->ascent,
5544                                                 2, font->ascent + 1, FALSE);
5545                                                                                           
5546          }
5547       
5548       if (text->cursor_char)
5549         {
5550           if (font->type == GDK_FONT_FONT)
5551             gdk_gc_set_font (text->gc, font);
5552
5553           gdk_gc_set_foreground (text->gc, MARK_CURRENT_FORE (text, &text->cursor_mark));
5554
5555           gdk_draw_text_wc (text->text_area, font,
5556                          text->gc,
5557                          text->cursor_pos_x,
5558                          text->cursor_pos_y - text->cursor_char_offset,
5559                          &text->cursor_char,
5560                          1);
5561         }
5562
5563         gdk_gc_copy(text->gc, gc);
5564         gdk_gc_unref(gc);
5565     }
5566 }
5567
5568 static gint
5569 drawn_cursor_min (GtkSText* text)
5570 {
5571   GdkFont* font;
5572   
5573   g_assert(text->cursor_mark.property);
5574   
5575   font = MARK_CURRENT_FONT(text, &text->cursor_mark);
5576   
5577   return text->cursor_pos_y - text->cursor_char_offset - font->ascent;
5578 }
5579
5580 static gint
5581 drawn_cursor_max (GtkSText* text)
5582 {
5583   GdkFont* font;
5584   
5585   g_assert(text->cursor_mark.property);
5586   
5587   font = MARK_CURRENT_FONT(text, &text->cursor_mark);
5588   
5589   return text->cursor_pos_y - text->cursor_char_offset;
5590 }
5591
5592 static void
5593 draw_cursor (GtkSText* text, gint absolute)
5594 {
5595   GtkEditable *editable = (GtkEditable *)text;
5596   gint pixel_width, pixel_height;
5597   
5598   TDEBUG (("in draw_cursor\n"));
5599   
5600   if (absolute)
5601     text->cursor_drawn_level = 1;
5602   
5603   if ((--text->cursor_drawn_level == 0) &&
5604       editable->editable &&
5605       (editable->selection_start_pos == editable->selection_end_pos) &&
5606       GTK_WIDGET_DRAWABLE (text) && text->line_start_cache)
5607     {
5608       GdkFont* font;
5609           GdkGC*          gc;
5610       
5611       g_assert (text->cursor_mark.property);
5612
5613           gc = gdk_gc_new(text->text_area);
5614           g_assert (gc);
5615           gdk_gc_copy(gc, text->gc);
5616           font = MARK_CURRENT_FONT (text, &text->cursor_mark);
5617           if (text->cursor_type == STEXT_CURSOR_BLOCK) {
5618                   /* SYLPHEED:
5619                    * changed the cursor to a real block (TM)
5620                    */
5621                   if (text->use_wchar) {
5622                         pixel_width = gdk_char_width_wc(font, text->cursor_char);               
5623                   }
5624                   else {
5625                         pixel_width = gdk_char_width(font, text->cursor_char);
5626                   }
5627                   pixel_width -= 1;
5628
5629                   pixel_height = LINE_HEIGHT(CACHE_DATA(text->current_line));
5630                   gdk_gc_set_foreground (text->gc, &GTK_WIDGET (text)->style->text[GTK_STATE_NORMAL]);
5631                   gdk_gc_set_function(text->gc, GDK_INVERT);
5632                   gdk_draw_rectangle(text->text_area, text->gc, TRUE, 
5633                                                          text->cursor_pos_x, 
5634                                                          text->cursor_pos_y - pixel_height,
5635                                                          pixel_width, 
5636                                                          pixel_height);
5637           }
5638           else {
5639                 gdk_gc_set_line_attributes(text->gc, 2, GDK_LINE_SOLID, GDK_CAP_NOT_LAST, GDK_JOIN_MITER);
5640                 gdk_gc_set_foreground(text->gc, &GTK_WIDGET (text)->style->text[GTK_STATE_NORMAL]);
5641             gdk_draw_line(text->text_area, text->gc, text->cursor_pos_x,
5642                               text->cursor_pos_y - text->cursor_char_offset,
5643                                           text->cursor_pos_x,
5644                                           text->cursor_pos_y - text->cursor_char_offset - font->ascent);
5645                                                                                                    
5646           }
5647           gdk_gc_copy(text->gc, gc);                                            
5648           gdk_gc_unref(gc);
5649     }
5650 }
5651
5652 static GdkGC *
5653 create_bg_gc (GtkSText *text)
5654 {
5655   GdkGCValues values;
5656   
5657   values.tile = GTK_WIDGET (text)->style->bg_pixmap[GTK_STATE_NORMAL];
5658   values.fill = GDK_TILED;
5659
5660   return gdk_gc_new_with_values (text->text_area, &values,
5661                                  GDK_GC_FILL | GDK_GC_TILE);
5662 }
5663
5664 static void
5665 clear_area (GtkSText *text, GdkRectangle *area)
5666 {
5667   GtkWidget *widget = GTK_WIDGET (text);
5668   
5669   if (text->bg_gc)
5670     {
5671       gint width, height;
5672       
5673       gdk_window_get_size (widget->style->bg_pixmap[GTK_STATE_NORMAL], &width, &height);
5674       
5675       gdk_gc_set_ts_origin (text->bg_gc,
5676                             (- (gint)text->first_onscreen_hor_pixel) % width,
5677                             (- (gint)text->first_onscreen_ver_pixel) % height);
5678
5679       gdk_draw_rectangle (text->text_area, text->bg_gc, TRUE,
5680                           area->x, area->y, area->width, area->height);
5681     }
5682   else
5683     gdk_window_clear_area (text->text_area, area->x, area->y, area->width, area->height);
5684 }
5685
5686 static void
5687 expose_text (GtkSText* text, GdkRectangle *area, gboolean cursor)
5688 {
5689   GList *cache = text->line_start_cache;
5690   gint pixels = - text->first_cut_pixels;
5691   gint min_y = MAX (0, area->y);
5692   gint max_y = MAX (0, area->y + area->height);
5693   gint height;
5694   
5695   gdk_window_get_size (text->text_area, NULL, &height);
5696   max_y = MIN (max_y, height);
5697   
5698   TDEBUG (("in expose x=%d y=%d w=%d h=%d\n", area->x, area->y, area->width, area->height));
5699   
5700   clear_area (text, area);
5701   
5702   for (; pixels < height; cache = cache->next)
5703     {
5704       if (pixels < max_y && (pixels + (gint)LINE_HEIGHT(CACHE_DATA(cache))) >= min_y)
5705         {
5706           draw_line (text, pixels, &CACHE_DATA(cache));
5707           
5708           if (CACHE_DATA(cache).wraps)
5709             draw_line_wrap (text, pixels + CACHE_DATA(cache).font_ascent);
5710         }
5711       
5712       if (cursor && GTK_WIDGET_HAS_FOCUS (text))
5713         {
5714           if (CACHE_DATA(cache).start.index <= text->cursor_mark.index &&
5715               CACHE_DATA(cache).end.index >= text->cursor_mark.index)
5716             {
5717               /* We undraw and draw the cursor here to get the drawn
5718                * level right ... FIXME - maybe the second parameter
5719                * of draw_cursor should work differently
5720                */
5721               undraw_cursor (text, FALSE);
5722               draw_cursor (text, FALSE);
5723             }
5724         }
5725       
5726       pixels += LINE_HEIGHT(CACHE_DATA(cache));
5727       
5728       if (!cache->next)
5729         {
5730           fetch_lines_forward (text, 1);
5731           
5732           if (!cache->next)
5733             break;
5734         }
5735     }
5736 }
5737
5738 static void 
5739 gtk_stext_update_text    (GtkEditable       *editable,
5740                          gint               start_pos,
5741                          gint               end_pos)
5742 {
5743   GtkSText *text = GTK_STEXT (editable);
5744   
5745   GList *cache = text->line_start_cache;
5746   gint pixels = - text->first_cut_pixels;
5747   GdkRectangle area;
5748   gint width;
5749   gint height;
5750   
5751   if (end_pos < 0)
5752     end_pos = TEXT_LENGTH (text);
5753   
5754   if (end_pos < start_pos)
5755     return;
5756   
5757   gdk_window_get_size (text->text_area, &width, &height);
5758   area.x = 0;
5759   area.y = -1;
5760   area.width = width;
5761   area.height = 0;
5762   
5763   TDEBUG (("in expose span start=%d stop=%d\n", start_pos, end_pos));
5764   
5765   for (; pixels < height; cache = cache->next)
5766     {
5767       if (CACHE_DATA(cache).start.index < end_pos)
5768         {
5769           if (CACHE_DATA(cache).end.index >= start_pos)
5770             {
5771               if (area.y < 0)
5772                 area.y = MAX(0,pixels);
5773               area.height = pixels + LINE_HEIGHT(CACHE_DATA(cache)) - area.y;
5774             }
5775         }
5776       else
5777         break;
5778       
5779       pixels += LINE_HEIGHT(CACHE_DATA(cache));
5780       
5781       if (!cache->next)
5782         {
5783           fetch_lines_forward (text, 1);
5784           
5785           if (!cache->next)
5786             break;
5787         }
5788     }
5789   
5790   if (area.y >= 0)
5791     expose_text (text, &area, TRUE);
5792 }
5793
5794 static void
5795 recompute_geometry (GtkSText* text)
5796 {
5797   GtkSPropertyMark mark, start_mark;
5798   GList *new_lines;
5799   gint height;
5800   gint width;
5801   
5802   free_cache (text);
5803   
5804   mark = start_mark = set_vertical_scroll (text);
5805
5806   /* We need a real start of a line when calling fetch_lines().
5807    * not the start of a wrapped line.
5808    */
5809   while (mark.index > 0 &&
5810          GTK_STEXT_INDEX (text, mark.index - 1) != LINE_DELIM)
5811     decrement_mark (&mark);
5812
5813   gdk_window_get_size (text->text_area, &width, &height);
5814
5815   /* Fetch an entire line, to make sure that we get all the text
5816    * we backed over above, in addition to enough text to fill up
5817    * the space vertically
5818    */
5819
5820   new_lines = fetch_lines (text,
5821                            &mark,
5822                            NULL,
5823                            FetchLinesCount,
5824                            1);
5825
5826   mark = CACHE_DATA (g_list_last (new_lines)).end;
5827   if (!LAST_INDEX (text, mark))
5828     {
5829       advance_mark (&mark);
5830
5831       new_lines = g_list_concat (new_lines, 
5832                                  fetch_lines (text,
5833                                               &mark,
5834                                               NULL,
5835                                               FetchLinesPixels,
5836                                               height + text->first_cut_pixels));
5837     }
5838
5839   /* Now work forward to the actual first onscreen line */
5840
5841   while (CACHE_DATA (new_lines).start.index < start_mark.index)
5842     new_lines = new_lines->next;
5843   
5844   text->line_start_cache = new_lines;
5845   
5846   find_cursor (text, TRUE);
5847 }
5848
5849 /**********************************************************************/
5850 /*                            Selection                               */
5851 /**********************************************************************/
5852
5853 static void 
5854 gtk_stext_set_selection  (GtkEditable   *editable,
5855                          gint           start,
5856                          gint           end)
5857 {
5858   GtkSText *text = GTK_STEXT (editable);
5859   
5860   guint start1, end1, start2, end2;
5861   
5862   if (end < 0)
5863     end = TEXT_LENGTH (text);
5864   
5865   start1 = MIN(start,end);
5866   end1 = MAX(start,end);
5867   start2 = MIN(editable->selection_start_pos, editable->selection_end_pos);
5868   end2 = MAX(editable->selection_start_pos, editable->selection_end_pos);
5869   
5870   if (start2 < start1)
5871     {
5872       guint tmp;
5873       
5874       tmp = start1; start1 = start2; start2 = tmp;
5875       tmp = end1;   end1   = end2;   end2   = tmp;
5876     }
5877   
5878   undraw_cursor (text, FALSE);
5879   editable->selection_start_pos = start;
5880   editable->selection_end_pos = end;
5881   draw_cursor (text, FALSE);
5882   
5883   /* Expose only what changed */
5884   
5885   if (start1 < start2)
5886     gtk_stext_update_text (editable, start1, MIN(end1, start2));
5887   
5888   if (end2 > end1)
5889     gtk_stext_update_text (editable, MAX(end1, start2), end2);
5890   else if (end2 < end1)
5891     gtk_stext_update_text (editable, end2, end1);
5892 }
5893
5894
5895 /* SYLPHEED:
5896  * cursor timer
5897  */
5898
5899 static gint stext_blink_timer_proc(GtkSText *text)
5900 {
5901         if (text->cursor_state_on) {
5902                 text->cursor_state_on = FALSE;
5903                 undraw_cursor(text, TRUE);
5904                 /* kill this timer... */
5905                 gtk_timeout_remove(text->cursor_timer_id);
5906                 text->cursor_timer_id = gtk_timeout_add(text->cursor_off_ms, (GtkFunction) stext_blink_timer_proc, (gpointer) text); 
5907         }
5908         else {
5909                 text->cursor_state_on = TRUE;
5910                 draw_cursor(text, TRUE);
5911                 /* kill this timer... */
5912                 gtk_timeout_remove(text->cursor_timer_id);
5913                 text->cursor_timer_id = gtk_timeout_add(text->cursor_on_ms, (GtkFunction) stext_blink_timer_proc, (gpointer) text);
5914         }
5915         return TRUE;
5916 }
5917
5918 static gint stext_idle_timer_proc(GtkSText *text) 
5919 {
5920         /* make sure the cursor timer is off */
5921         if (text->cursor_timer_id) {
5922                 gtk_timeout_remove(text->cursor_timer_id);
5923                 text->cursor_timer_id = 0;
5924         }
5925         /* assuming it's always on when calling this function ... */
5926         text->cursor_state_on = TRUE;
5927         text->cursor_timer_id = gtk_timeout_add(text->cursor_on_ms, (GtkFunction) stext_blink_timer_proc, (gpointer) text); 
5928         /* make sure we kill the timer (could perhaps make this function return FALSE (not documented in
5929          * the current docs). should check the source. */
5930         gtk_idle_remove( text->cursor_idle_time_timer_id ); 
5931         text->cursor_idle_time_timer_id = 0;
5932         return TRUE;
5933 }
5934
5935 static void gtk_stext_enable_blink       (GtkSText *text)
5936 {
5937         if (text->cursor_timer_on) { 
5938                 gtk_stext_disable_blink(text);
5939                 text->cursor_idle_time_timer_id = gtk_idle_add((GtkFunction) stext_idle_timer_proc, (gpointer) text);
5940         }
5941 }
5942
5943 static void gtk_stext_disable_blink (GtkSText *text)
5944 {
5945         if (text->cursor_timer_on) {
5946                 if (text->cursor_idle_time_timer_id) {
5947                         gtk_idle_remove( text->cursor_idle_time_timer_id );
5948                         text->cursor_idle_time_timer_id = 0;
5949                 }
5950                 if (text->cursor_timer_id) {
5951                         gtk_timeout_remove( text->cursor_timer_id );
5952                         text->cursor_timer_id = 0;
5953                 }
5954                 draw_cursor(text, TRUE);
5955         }               
5956 }
5957
5958 void gtk_stext_set_blink(GtkSText *text, gboolean blinkin_on)
5959 {
5960         if (text->cursor_timer_on != blinkin_on) {
5961                 if (text->cursor_timer_on) {
5962                         /* text widget already created? */
5963                         if (text->cursor_visible) {
5964                                 gtk_stext_disable_blink(text);
5965                         }                               
5966                         text->cursor_timer_on = FALSE;
5967                 }
5968                 else {
5969                         if (text->cursor_visible) {
5970                                 gtk_stext_enable_blink(text);
5971                         }
5972                         text->cursor_timer_on = TRUE;
5973                 }
5974         }
5975 }
5976
5977
5978 void  gtk_stext_set_wrap_rmargin (GtkSText *text, gint rmargin)
5979 {
5980         /* not particularly impressive, but it does the job.  */
5981         /* TODO: currently only allowed to set this after a
5982          * gtk_stext_new() */
5983         text->wrap_rmargin = rmargin >= 0 ? rmargin : 0; 
5984 }
5985
5986 /**********************************************************************/
5987 /*                              Debug                                 */
5988 /**********************************************************************/
5989
5990 #ifdef DEBUG_GTK_STEXT
5991 static void
5992 gtk_stext_show_cache_line (GtkSText *text, GList *cache,
5993                           const char* what, const char* func, gint line)
5994 {
5995   LineParams *lp = &CACHE_DATA(cache);
5996   gint i;
5997   
5998   if (cache == text->line_start_cache)
5999     g_message ("Line Start Cache: ");
6000   
6001   if (cache == text->current_line)
6002     g_message("Current Line: ");
6003   
6004   g_message ("%s:%d: cache line %s s=%d,e=%d,lh=%d (",
6005              func,
6006              line,
6007              what,
6008              lp->start.index,
6009              lp->end.index,
6010              LINE_HEIGHT(*lp));
6011   
6012   for (i = lp->start.index; i < (lp->end.index + lp->wraps); i += 1)
6013     g_message ("%c", GTK_STEXT_INDEX (text, i));
6014   
6015   g_message (")\n");
6016 }
6017
6018 static void
6019 gtk_stext_show_cache (GtkSText *text, const char* func, gint line)
6020 {
6021   GList *l = text->line_start_cache;
6022   
6023   if (!l) {
6024     return;
6025   }
6026   
6027   /* back up to the absolute beginning of the line cache */
6028   while (l->prev)
6029     l = l->prev;
6030   
6031   g_message ("*** line cache ***\n");
6032   for (; l; l = l->next)
6033     gtk_stext_show_cache_line (text, l, "all", func, line);
6034 }
6035
6036 static void
6037 gtk_stext_assert_mark (GtkSText         *text,
6038                       GtkSPropertyMark *mark,
6039                       GtkSPropertyMark *before,
6040                       GtkSPropertyMark *after,
6041                       const gchar     *msg,
6042                       const gchar     *where,
6043                       gint             line)
6044 {
6045   GtkSPropertyMark correct_mark = find_mark (text, mark->index);
6046   
6047   if (mark->offset != correct_mark.offset ||
6048       mark->property != correct_mark.property)
6049     g_warning ("incorrect %s text property marker in %s:%d, index %d -- bad!", where, msg, line, mark->index);
6050 }
6051
6052 static void
6053 gtk_stext_assert (GtkSText         *text,
6054                  const gchar     *msg,
6055                  gint             line)
6056 {
6057   GList* cache = text->line_start_cache;
6058   GtkSPropertyMark* before_mark = NULL;
6059   GtkSPropertyMark* after_mark = NULL;
6060   
6061   gtk_stext_show_props (text, msg, line);
6062   
6063   for (; cache->prev; cache = cache->prev)
6064     /* nothing */;
6065   
6066   g_message ("*** line markers ***\n");
6067   
6068   for (; cache; cache = cache->next)
6069     {
6070       after_mark = &CACHE_DATA(cache).end;
6071       gtk_stext_assert_mark (text, &CACHE_DATA(cache).start, before_mark, after_mark, msg, "start", line);
6072       before_mark = &CACHE_DATA(cache).start;
6073       
6074       if (cache->next)
6075         after_mark = &CACHE_DATA(cache->next).start;
6076       else
6077         after_mark = NULL;
6078       
6079       gtk_stext_assert_mark (text, &CACHE_DATA(cache).end, before_mark, after_mark, msg, "end", line);
6080       before_mark = &CACHE_DATA(cache).end;
6081     }
6082 }
6083
6084 static void
6085 gtk_stext_show_adj (GtkSText *text,
6086                    GtkAdjustment *adj,
6087                    const char* what,
6088                    const char* func,
6089                    gint line)
6090 {
6091   g_message ("*** adjustment ***\n");
6092   
6093   g_message ("%s:%d: %s adjustment l=%.1f u=%.1f v=%.1f si=%.1f pi=%.1f ps=%.1f\n",
6094              func,
6095              line,
6096              what,
6097              adj->lower,
6098              adj->upper,
6099              adj->value,
6100              adj->step_increment,
6101              adj->page_increment,
6102              adj->page_size);
6103 }
6104
6105 static void
6106 gtk_stext_show_props (GtkSText *text,
6107                      const char* msg,
6108                      int line)
6109 {
6110   GList* props = text->text_properties;
6111   int proplen = 0;
6112   
6113   g_message ("%s:%d: ", msg, line);
6114   
6115   for (; props; props = props->next)
6116     {
6117       TextProperty *p = (TextProperty*)props->data;
6118       
6119       proplen += p->length;
6120
6121       g_message ("[%d,%p,", p->length, p);
6122       if (p->flags & PROPERTY_FONT)
6123         g_message ("%p,", p->font);
6124       else
6125         g_message ("-,");
6126       if (p->flags & PROPERTY_FOREGROUND)
6127         g_message ("%ld, ", p->fore_color.pixel);
6128       else
6129         g_message ("-,");
6130       if (p->flags & PROPERTY_BACKGROUND)
6131         g_message ("%ld] ", p->back_color.pixel);
6132       else
6133         g_message ("-] ");
6134     }
6135   
6136   g_message ("\n");
6137   
6138   if (proplen - 1 != TEXT_LENGTH(text))
6139     g_warning ("incorrect property list length in %s:%d -- bad!", msg, line);
6140 }
6141 #endif