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