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