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