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