sync with sylpheed 0.7.0cvs12
[claws.git] / src / textview.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gdk/gdk.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gtk/gtkvbox.h>
30 #include <gtk/gtkscrolledwindow.h>
31 #include <gtk/gtksignal.h>
32 #include <stdio.h>
33 #include <ctype.h>
34 #include <string.h>
35 #include <stdlib.h>
36
37 #include "intl.h"
38 #include "main.h"
39 #include "summaryview.h"
40 #include "procheader.h"
41 #include "prefs_common.h"
42 #include "codeconv.h"
43 #include "gtkstext.h"
44 #include "utils.h"
45 #include "gtkutils.h"
46 #include "procmime.h"
47 #include "html.h"
48 #include "enriched.h"
49 #include "compose.h"
50 #include "addressbook.h"
51 #include "displayheader.h"
52 #include "account.h"
53
54 #define FONT_LOAD(font, s) \
55 { \
56         gchar *fontstr, *p; \
57  \
58         Xstrdup_a(fontstr, s, ); \
59         if ((p = strchr(fontstr, ',')) != NULL) *p = '\0'; \
60         font = gdk_font_load(fontstr); \
61         if (!font) \
62                 g_warning("Couldn't load the font '%s'\n", fontstr); \
63 }
64
65 typedef struct _RemoteURI       RemoteURI;
66
67 struct _RemoteURI
68 {
69         gchar *uri;
70
71         guint start;
72         guint end;
73 };
74
75 static GdkColor quote_colors[3] = {
76         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
77         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
78         {(gulong)0, (gushort)0, (gushort)0, (gushort)0}
79 };
80
81 static GdkColor uri_color = {
82         (gulong)0,
83         (gushort)0,
84         (gushort)0,
85         (gushort)0
86 };
87
88 static GdkColor emphasis_color = {
89         (gulong)0,
90         (gushort)0,
91         (gushort)0,
92         (gushort)0xcfff
93 };
94
95 static GdkColor error_color = {
96         (gulong)0,
97         (gushort)0xefff,
98         (gushort)0,
99         (gushort)0
100 };
101
102 static GdkFont *spacingfont;
103
104 static void textview_show_ertf          (TextView       *textview,
105                                          FILE           *fp,
106                                          CodeConverter  *conv);
107 static void textview_show_html          (TextView       *textview,
108                                          FILE           *fp,
109                                          CodeConverter  *conv);
110 static void textview_write_line         (TextView       *textview,
111                                          const gchar    *str,
112                                          CodeConverter  *conv);
113 static void textview_write_link         (TextView       *textview,
114                                          const gchar    *url,
115                                          const gchar    *str,
116                                          CodeConverter  *conv);
117 static GPtrArray *textview_scan_header  (TextView       *textview,
118                                          FILE           *fp);
119 static void textview_show_header        (TextView       *textview,
120                                          GPtrArray      *headers);
121
122 static void textview_key_pressed        (GtkWidget      *widget,
123                                          GdkEventKey    *event,
124                                          TextView       *textview);
125 static gint textview_button_pressed     (GtkWidget      *widget,
126                                          GdkEventButton *event,
127                                          TextView       *textview);
128 static gint textview_button_released    (GtkWidget      *widget,
129                                          GdkEventButton *event,
130                                          TextView       *textview);
131
132 static void textview_uri_list_remove_all(GSList         *uri_list);
133
134 static void textview_smooth_scroll_do           (TextView       *textview,
135                                                  gfloat          old_value,
136                                                  gfloat          last_value,
137                                                  gint            step);
138 static void textview_smooth_scroll_one_line     (TextView       *textview,
139                                                  gboolean        up);
140 static gboolean textview_smooth_scroll_page     (TextView       *textview,
141                                                  gboolean        up);
142
143
144 TextView *textview_create(void)
145 {
146         TextView *textview;
147         GtkWidget *vbox;
148         GtkWidget *scrolledwin_sb;
149         GtkWidget *scrolledwin_mb;
150         GtkWidget *text_sb;
151         GtkWidget *text_mb;
152
153         debug_print(_("Creating text view...\n"));
154         textview = g_new0(TextView, 1);
155
156         scrolledwin_sb = gtk_scrolled_window_new(NULL, NULL);
157         scrolledwin_mb = gtk_scrolled_window_new(NULL, NULL);
158         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin_sb),
159                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
160         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin_mb),
161                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
162         gtk_widget_set_usize(scrolledwin_sb, prefs_common.mainview_width, -1);
163         gtk_widget_set_usize(scrolledwin_mb, prefs_common.mainview_width, -1);
164
165         /* create GtkSText widgets for single-byte and multi-byte character */
166         text_sb = gtk_stext_new(NULL, NULL);
167         text_mb = gtk_stext_new(NULL, NULL);
168         GTK_STEXT(text_sb)->default_tab_width = 8;
169         GTK_STEXT(text_mb)->default_tab_width = 8;
170         gtk_widget_show(text_sb);
171         gtk_widget_show(text_mb);
172         gtk_stext_set_word_wrap(GTK_STEXT(text_sb), TRUE);
173         gtk_stext_set_word_wrap(GTK_STEXT(text_mb), TRUE);
174         gtk_widget_ensure_style(text_sb);
175         gtk_widget_ensure_style(text_mb);
176         if (text_sb->style && text_sb->style->font->type == GDK_FONT_FONTSET) {
177                 GtkStyle *style;
178                 GdkFont *font;
179
180                 FONT_LOAD(font, prefs_common.normalfont);
181                 if (font) {
182                         style = gtk_style_copy(text_sb->style);
183                         gdk_font_unref(style->font);
184                         style->font = font;
185                         gtk_widget_set_style(text_sb, style);
186                 }
187         }
188         if (text_mb->style && text_mb->style->font->type == GDK_FONT_FONT) {
189                 GtkStyle *style;
190                 GdkFont *font;
191
192                 font = gdk_fontset_load(prefs_common.normalfont);
193                 if (font) {
194                         style = gtk_style_copy(text_mb->style);
195                         gdk_font_unref(style->font);
196                         style->font = font;
197                         gtk_widget_set_style(text_mb, style);
198                 }
199         }
200         gtk_widget_ref(scrolledwin_sb);
201         gtk_widget_ref(scrolledwin_mb);
202
203         gtk_container_add(GTK_CONTAINER(scrolledwin_sb), text_sb);
204         gtk_container_add(GTK_CONTAINER(scrolledwin_mb), text_mb);
205         gtk_signal_connect(GTK_OBJECT(text_sb), "key_press_event",
206                            GTK_SIGNAL_FUNC(textview_key_pressed),
207                            textview);
208         gtk_signal_connect_after(GTK_OBJECT(text_sb), "button_press_event",
209                                  GTK_SIGNAL_FUNC(textview_button_pressed),
210                                  textview);
211         gtk_signal_connect_after(GTK_OBJECT(text_sb), "button_release_event",
212                                  GTK_SIGNAL_FUNC(textview_button_released),
213                                  textview);
214         gtk_signal_connect(GTK_OBJECT(text_mb), "key_press_event",
215                            GTK_SIGNAL_FUNC(textview_key_pressed),
216                            textview);
217         gtk_signal_connect_after(GTK_OBJECT(text_mb), "button_press_event",
218                                  GTK_SIGNAL_FUNC(textview_button_pressed),
219                                  textview);
220         gtk_signal_connect_after(GTK_OBJECT(text_mb), "button_release_event",
221                                  GTK_SIGNAL_FUNC(textview_button_released),
222                                  textview);
223
224         gtk_widget_show(scrolledwin_sb);
225         gtk_widget_show(scrolledwin_mb);
226
227         vbox = gtk_vbox_new(FALSE, 0);
228         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin_sb, TRUE, TRUE, 0);
229
230         textview->vbox           = vbox;
231         textview->scrolledwin    = scrolledwin_sb;
232         textview->scrolledwin_sb = scrolledwin_sb;
233         textview->scrolledwin_mb = scrolledwin_mb;
234         textview->text           = text_sb;
235         textview->text_sb        = text_sb;
236         textview->text_mb        = text_mb;
237         textview->text_is_mb     = FALSE;
238         textview->uri_list       = NULL;
239         textview->body_pos       = 0;
240         textview->cur_pos        = 0;
241         textview->last_buttonpress = GDK_NOTHING;
242
243         return textview;
244 }
245
246 void textview_init(TextView *textview)
247 {
248         gtkut_widget_disable_theme_engine(textview->text_sb);
249         gtkut_widget_disable_theme_engine(textview->text_mb);
250         textview_update_message_colors();
251         textview_set_font(textview, NULL);
252 }
253
254 void textview_update_message_colors(void)
255 {
256         GdkColor black = {0, 0, 0, 0};
257
258         if (prefs_common.enable_color) {
259                 /* grab the quote colors, converting from an int to a GdkColor */
260                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
261                                                &quote_colors[0]);
262                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level2_col,
263                                                &quote_colors[1]);
264                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level3_col,
265                                                &quote_colors[2]);
266                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
267                                                &uri_color);
268         } else {
269                 quote_colors[0] = quote_colors[1] = quote_colors[2] = 
270                         uri_color = emphasis_color = black;
271         }
272 }
273
274 void textview_show_message(TextView *textview, MimeInfo *mimeinfo,
275                            const gchar *file)
276 {
277         FILE *fp;
278
279         if ((fp = fopen(file, "r")) == NULL) {
280                 FILE_OP_ERROR(file, "fopen");
281                 return;
282         }
283
284         textview_show_part(textview, mimeinfo, fp);
285
286         fclose(fp);
287 }
288
289 void textview_show_part(TextView *textview, MimeInfo *mimeinfo, FILE *fp)
290 {
291         GtkSText *text;
292         gchar buf[BUFFSIZE];
293         const gchar *boundary = NULL;
294         gint boundary_len = 0;
295         const gchar *charset = NULL;
296         FILE *tmpfp;
297         GPtrArray *headers = NULL;
298         CodeConverter *conv;
299
300         g_return_if_fail(mimeinfo != NULL);
301         g_return_if_fail(fp != NULL);
302
303         if (mimeinfo->mime_type == MIME_MULTIPART) {
304                 if (mimeinfo->sub) {
305                         mimeinfo = mimeinfo->sub;
306                         if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0) {
307                                 perror("fseek");
308                                 return;
309                         }
310                 } else
311                         return;
312         }
313         if (mimeinfo->parent && mimeinfo->parent->boundary) {
314                 boundary = mimeinfo->parent->boundary;
315                 boundary_len = strlen(boundary);
316         }
317
318         if (!boundary && (mimeinfo->mime_type == MIME_TEXT || mimeinfo->mime_type == MIME_TEXT_HTML || mimeinfo->mime_type == MIME_TEXT_ENRICHED)) {
319         
320                 if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
321                         perror("fseek");
322                 headers = textview_scan_header(textview, fp);
323         } else {
324                 if (mimeinfo->mime_type == MIME_TEXT && mimeinfo->parent) {
325                         glong fpos;
326                         MimeInfo *parent = mimeinfo->parent;
327
328                         while (parent->parent) {
329                                 if (parent->main &&
330                                     parent->main->mime_type ==
331                                         MIME_MESSAGE_RFC822)
332                                         break;
333                                 parent = parent->parent;
334                         }
335
336                         if ((fpos = ftell(fp)) < 0)
337                                 perror("ftell");
338                         else if (fseek(fp, parent->fpos, SEEK_SET) < 0)
339                                 perror("fseek");
340                         else {
341                                 headers = textview_scan_header(textview, fp);
342                                 if (fseek(fp, fpos, SEEK_SET) < 0)
343                                         perror("fseek");
344                         }
345                 }
346                 /* skip MIME part headers */
347                 while (fgets(buf, sizeof(buf), fp) != NULL)
348                         if (buf[0] == '\r' || buf[0] == '\n') break;
349         }
350
351         /* display attached RFC822 single text message */
352         if (mimeinfo->parent && mimeinfo->mime_type == MIME_MESSAGE_RFC822) {
353                 if (headers) procheader_header_array_destroy(headers);
354                 if (!mimeinfo->sub || mimeinfo->sub->children) return;
355                 headers = textview_scan_header(textview, fp);
356                 mimeinfo = mimeinfo->sub;
357         } else if (!mimeinfo->parent &&
358                    mimeinfo->mime_type == MIME_MESSAGE_RFC822) {
359                 if (headers) procheader_header_array_destroy(headers);
360                 if (!mimeinfo->sub) return;
361                 headers = textview_scan_header(textview, fp);
362                 mimeinfo = mimeinfo->sub;
363         }
364
365         if (prefs_common.force_charset)
366                 charset = prefs_common.force_charset;
367         else if (mimeinfo->charset)
368                 charset = mimeinfo->charset;
369         textview_set_font(textview, charset);
370
371         conv = conv_code_converter_new(charset);
372
373         textview_clear(textview);
374         text = GTK_STEXT(textview->text);
375         gtk_stext_freeze(text);
376
377         textview->body_pos = 0;
378         textview->cur_pos  = 0;
379
380         if (headers) {
381                 textview_show_header(textview, headers);
382                 procheader_header_array_destroy(headers);
383         }
384
385         tmpfp = procmime_decode_content(NULL, fp, mimeinfo);
386         if (tmpfp) {
387                 if (mimeinfo->mime_type == MIME_TEXT_HTML)
388                         textview_show_html(textview, tmpfp, conv);
389                 else if (mimeinfo->mime_type == MIME_TEXT_ENRICHED)
390                         textview_show_ertf(textview, tmpfp, conv);
391                 else
392                         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
393                                 textview_write_line(textview, buf, conv);
394                 fclose(tmpfp);
395         }
396
397         conv_code_converter_destroy(conv);
398
399         gtk_stext_thaw(text);
400 }
401
402 #define TEXT_INSERT(str) \
403         gtk_stext_insert(text, textview->msgfont, NULL, NULL, str, -1)
404
405 void textview_show_mime_part(TextView *textview, MimeInfo *partinfo)
406 {
407         GtkSText *text;
408
409         if (!partinfo) return;
410
411         textview_set_font(textview, NULL);
412         text = GTK_STEXT(textview->text);
413         textview_clear(textview);
414
415         gtk_stext_freeze(text);
416
417         TEXT_INSERT(_("To save this part, pop up the context menu with "));
418         TEXT_INSERT(_("right click and select `Save as...', "));
419         TEXT_INSERT(_("or press `y' key.\n\n"));
420
421         TEXT_INSERT(_("To display this part as a text message, select "));
422         TEXT_INSERT(_("`Display as text', or press `t' key.\n\n"));
423
424         TEXT_INSERT(_("To open this part with external program, select "));
425         TEXT_INSERT(_("`Open' or `Open with...', "));
426         TEXT_INSERT(_("or double-click, or click the center button, "));
427         TEXT_INSERT(_("or press `l' key."));
428
429         gtk_stext_thaw(text);
430 }
431
432 #if USE_GPGME
433 void textview_show_signature_part(TextView *textview, MimeInfo *partinfo)
434 {
435         GtkSText *text;
436
437         if (!partinfo) return;
438
439         textview_set_font(textview, NULL);
440         text = GTK_STEXT(textview->text);
441         textview_clear(textview);
442
443         gtk_stext_freeze(text);
444
445         if (partinfo->sigstatus_full == NULL) {
446                 TEXT_INSERT(_("This signature has not been checked yet.\n"));
447                 TEXT_INSERT(_("To check it, pop up the context menu with\n"));
448                 TEXT_INSERT(_("right click and select `Check signature'.\n"));
449         } else {
450                 TEXT_INSERT(partinfo->sigstatus_full);
451         }
452
453         gtk_stext_thaw(text);
454 }
455 #endif /* USE_GPGME */
456
457 #undef TEXT_INSERT
458
459 static void textview_show_html(TextView *textview, FILE *fp,
460                                CodeConverter *conv)
461 {
462         HTMLParser *parser;
463         gchar *str;
464         gchar* url = NULL;
465
466         parser = html_parser_new(fp, conv);
467         g_return_if_fail(parser != NULL);
468
469         while ((str = html_parse(parser)) != NULL) {
470                 if (parser->state == HTML_HREF) {
471                         /* first time : get and copy the URL */
472                         if (url == NULL) {
473                                 /* ALF - the sylpheed html parser returns an empty string,
474                                  * if still inside an <a>, but already parsed past HREF */
475                                 str = strtok(str, " ");
476                                 if (str) { 
477                                         url = strdup(str);
478                                         /* the URL may (or not) be followed by the
479                                          * referenced text */
480                                         str = strtok(NULL, "");
481                                 }       
482                         }
483                         if (str != NULL) {
484                                 textview_write_link(textview, url, str, NULL);
485                         }
486                 } else {
487                         if (url != NULL) {
488                                 free(url);
489                                 url = NULL;
490                         }
491                         textview_write_line(textview, str, NULL);
492                 }
493         }
494         html_parser_destroy(parser);
495 }
496
497 static void textview_show_ertf(TextView *textview, FILE *fp,
498                                CodeConverter *conv)
499 {
500         ERTFParser *parser;
501         gchar *str;
502         gchar* url = NULL;
503
504         parser = ertf_parser_new(fp, conv);
505         g_return_if_fail(parser != NULL);
506
507         while ((str = ertf_parse(parser)) != NULL) {
508                 textview_write_line(textview, str, NULL);
509         }
510         ertf_parser_destroy(parser);
511 }
512
513 /* get_uri_part() - retrieves a URI starting from scanpos.
514                     Returns TRUE if succesful */
515 static gboolean get_uri_part(const gchar *start, const gchar *scanpos,
516                              const gchar **bp, const gchar **ep)
517 {
518         const gchar *ep_;
519
520         g_return_val_if_fail(start != NULL, FALSE);
521         g_return_val_if_fail(scanpos != NULL, FALSE);
522         g_return_val_if_fail(bp != NULL, FALSE);
523         g_return_val_if_fail(ep != NULL, FALSE);
524
525         *bp = scanpos;
526
527         /* find end point of URI */
528         for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
529                 if (!isgraph(*ep_) || !isascii(*ep_) || strchr("()<>\"", *ep_))
530                         break;
531         }
532
533         /* no punctuation at end of string */
534
535         /* FIXME: this stripping of trailing punctuations may bite with other URIs.
536          * should pass some URI type to this function and decide on that whether
537          * to perform punctuation stripping */
538
539 #define IS_REAL_PUNCT(ch)       (ispunct(ch) && ((ch) != '/')) 
540
541         for (; ep_ - 1 > scanpos + 1 && IS_REAL_PUNCT(*(ep_ - 1)); ep_--)
542                 ;
543
544 #undef IS_REAL_PUNCT
545
546         *ep = ep_;
547
548         return TRUE;            
549 }
550
551 static gchar *make_uri_string(const gchar *bp, const gchar *ep)
552 {
553         return g_strndup(bp, ep - bp);
554 }
555
556 /* valid mail address characters */
557 #define IS_RFC822_CHAR(ch) \
558         (isascii(ch) && \
559          (ch) > 32   && \
560          (ch) != 127 && \
561          !isspace(ch) && \
562          !strchr("()<>\"", (ch)))
563
564 /* alphabet and number within 7bit ASCII */
565 #define IS_ASCII_ALNUM(ch)      (isascii(ch) && isalnum(ch))
566 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
567
568 /* get_email_part() - retrieves an email address. Returns TRUE if succesful */
569 static gboolean get_email_part(const gchar *start, const gchar *scanpos,
570                                const gchar **bp, const gchar **ep)
571 {
572         /* more complex than the uri part because we need to scan back and forward starting from
573          * the scan position. */
574         gboolean result = FALSE;
575         const gchar *bp_ = NULL;
576         const gchar *ep_ = NULL;
577
578         /* the informative part of the email address (describing the name
579          * of the email address owner) may contain quoted parts. the
580          * closure stack stores the last encountered quotes. */
581         gchar closure_stack[128];
582         gchar *ptr = closure_stack;
583
584         g_return_val_if_fail(start != NULL, FALSE);
585         g_return_val_if_fail(scanpos != NULL, FALSE);
586         g_return_val_if_fail(bp != NULL, FALSE);
587         g_return_val_if_fail(ep != NULL, FALSE);
588
589         /* scan start of address */
590         for (bp_ = scanpos - 1; bp_ >= start && IS_RFC822_CHAR(*bp_); bp_--)
591                 ;
592
593         /* TODO: should start with an alnum? */
594         bp_++;
595         for (; bp_ < scanpos && !IS_ASCII_ALNUM(*bp_); bp_++)
596                 ;
597
598         if (bp_ != scanpos) {
599                 /* scan end of address */
600                 for (ep_ = scanpos + 1; *ep_ && IS_RFC822_CHAR(*ep_); ep_++)
601                         ;
602
603                 /* TODO: really should terminate with an alnum? */
604                 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*ep_); --ep_)
605                         ;
606                 ep_++;
607
608                 if (ep_ > scanpos + 1) {
609                         *ep = ep_;
610                         *bp = bp_;
611                         result = TRUE;
612                 }
613         }
614
615         if (!result) return FALSE;
616
617         /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
618         if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_)) 
619                 return FALSE;
620
621         /* see if this is <bracketed>; in this case we also scan for the informative part. */
622         if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
623                 return TRUE;
624
625 #define FULL_STACK()    ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
626 #define IN_STACK()      (ptr > closure_stack)
627 /* has underrun check */
628 #define POP_STACK()     if(IN_STACK()) --ptr
629 /* has overrun check */
630 #define PUSH_STACK(c)   if(!FULL_STACK()) *ptr++ = (c); else return TRUE
631 /* has underrun check */
632 #define PEEK_STACK()    (IN_STACK() ? *(ptr - 1) : 0)
633
634         ep_++;
635
636         /* scan for the informative part. */
637         for (bp_ -= 2; bp_ >= start; bp_--) {
638                 /* if closure on the stack keep scanning */
639                 if (PEEK_STACK() == *bp_) {
640                         POP_STACK();
641                         continue;
642                 }
643                 if (*bp_ == '\'' || *bp_ == '"') {
644                         PUSH_STACK(*bp_);
645                         continue;
646                 }
647
648                 /* if nothing in the closure stack, do the special conditions
649                  * the following if..else expression simply checks whether 
650                  * a token is acceptable. if not acceptable, the clause
651                  * should terminate the loop with a 'break' */
652                 if (!PEEK_STACK()) {
653                         if (*bp_ == '-'
654                         && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
655                         && (((bp_ + 1) < ep_)    && isalnum(*(bp_ + 1)))) {
656                                 /* hyphens are allowed, but only in
657                                    between alnums */
658                         } else if (!ispunct(*bp_)) {
659                                 /* but anything not being a punctiation
660                                    is ok */
661                         } else {
662                                 break; /* anything else is rejected */
663                         }
664                 }
665         }
666
667         bp_++;
668
669 #undef PEEK_STACK
670 #undef PUSH_STACK
671 #undef POP_STACK
672 #undef IN_STACK
673 #undef FULL_STACK
674
675         /* scan forward (should start with an alnum) */
676         for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
677                 ;
678
679         *ep = ep_;
680         *bp = bp_;
681
682         return result;
683 }
684
685 #undef IS_QUOTE
686 #undef IS_RFC822_CHAR
687
688 static gchar *make_email_string(const gchar *bp, const gchar *ep)
689 {
690         /* returns a mailto: URI; mailto: is also used to detect the
691          * uri type later on in the button_pressed signal handler */
692         gchar *tmp;
693         gchar *result;
694
695         tmp = g_strndup(bp, ep - bp);
696         result = g_strconcat("mailto:", tmp, NULL);
697         g_free(tmp);
698
699         return result;
700 }
701
702 #define ADD_TXT_POS(bp_, ep_, pti_) \
703         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
704                 last = last->next; \
705                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
706                 last->next = NULL; \
707         } else { \
708                 g_warning("alloc error scanning URIs\n"); \
709                 gtk_stext_insert(text, textview->msgfont, fg_color, NULL, \
710                                 linebuf, -1); \
711                 return; \
712         }
713
714 /* textview_make_clickable_parts() - colorizes clickable parts */
715 static void textview_make_clickable_parts(TextView *textview,
716                                           GdkFont *font,
717                                           GdkColor *fg_color,
718                                           GdkColor *uri_color,
719                                           const gchar *linebuf)
720 {
721         /* parse table - in order of priority */
722         struct table {
723                 const gchar *needle; /* token */
724
725                 /* token search function */
726                 gchar    *(*search)     (const gchar *haystack,
727                                          const gchar *needle);
728                 /* part parsing function */
729                 gboolean  (*parse)      (const gchar *start,
730                                          const gchar *scanpos,
731                                          const gchar **bp_,
732                                          const gchar **ep_);
733                 /* part to URI function */
734                 gchar    *(*build_uri)  (const gchar *bp,
735                                          const gchar *ep);
736         };
737
738         static struct table parser[] = {
739                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
740                 {"https://", strcasestr, get_uri_part,   make_uri_string},
741                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
742                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
743                 {"@",        strcasestr, get_email_part, make_email_string}
744         };
745         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
746
747         gint  n;
748         const gchar *walk, *bp, *ep;
749
750         struct txtpos {
751                 const gchar     *bp, *ep;       /* text position */
752                 gint             pti;           /* index in parse table */
753                 struct txtpos   *next;          /* next */
754         } head = {NULL, NULL, 0,  NULL}, *last = &head;
755
756         GtkSText *text = GTK_STEXT(textview->text);
757
758         /* parse for clickable parts, and build a list of begin and end positions  */
759         for (walk = linebuf, n = 0;;) {
760                 gint last_index = PARSE_ELEMS;
761                 gchar *scanpos = NULL;
762
763                 /* FIXME: this looks phony. scanning for anything in the parse table */
764                 for (n = 0; n < PARSE_ELEMS; n++) {
765                         gchar *tmp;
766
767                         tmp = parser[n].search(walk, parser[n].needle);
768                         if (tmp) {
769                                 if (scanpos == NULL || tmp < scanpos) {
770                                         scanpos = tmp;
771                                         last_index = n;
772                                 }
773                         }                                       
774                 }
775
776                 if (scanpos) {
777                         /* check if URI can be parsed */
778                         if (parser[last_index].parse(linebuf, scanpos, &bp, &ep)
779                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
780                                         ADD_TXT_POS(bp, ep, last_index);
781                                         walk = ep;
782                         } else
783                                 walk = scanpos +
784                                         strlen(parser[last_index].needle);
785                 } else
786                         break;
787         }
788
789         /* colorize this line */
790         if (head.next) {
791                 const gchar *normal_text = linebuf;
792
793                 /* insert URIs */
794                 for (last = head.next; last != NULL;
795                      normal_text = last->ep, last = last->next) {
796                         RemoteURI *uri;
797
798                         uri = g_new(RemoteURI, 1);
799                         if (last->bp - normal_text > 0)
800                                 gtk_stext_insert(text, font,
801                                                 fg_color, NULL,
802                                                 normal_text,
803                                                 last->bp - normal_text);
804                         uri->uri = parser[last->pti].build_uri(last->bp,
805                                                                last->ep);
806                         uri->start = gtk_stext_get_point(text);
807                         gtk_stext_insert(text, font, uri_color,
808                                         NULL, last->bp, last->ep - last->bp);
809                         uri->end = gtk_stext_get_point(text);
810                         textview->uri_list =
811                                 g_slist_append(textview->uri_list, uri);
812                 }
813
814                 if (*normal_text)
815                         gtk_stext_insert(text, font, fg_color,
816                                         NULL, normal_text, -1);
817         } else
818                 gtk_stext_insert(text, font, fg_color, NULL, linebuf, -1);
819 }
820
821 #undef ADD_TXT_POS
822
823 /* This function writes str as a double-clickable link with the given url. */ 
824 static void textview_write_link(TextView *textview, const gchar *url,
825                                 const gchar *str, CodeConverter *conv)
826 {
827     GdkColor *link_color = NULL;
828     RemoteURI* uri;
829     GtkSText *text = GTK_STEXT(textview->text);
830     gchar buf[BUFFSIZE];
831
832     /* this part is taken from textview_write_line. Right now the only place
833      * that calls this function passes NULL for conv, but you never know. */
834     if (!conv)
835             strncpy2(buf, str, sizeof(buf));
836     else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
837             gtk_stext_insert(text, textview->msgfont,
838                             prefs_common.enable_color
839                             ? &error_color : NULL, NULL,
840                             "*** Warning: code conversion failed ***\n",
841                             -1);
842             return;
843     }
844
845     /* this part is based on the code in make_clickable_parts */
846     if (prefs_common.enable_color) {
847         link_color = &uri_color;
848     }
849     uri = g_new(RemoteURI, 1);
850     uri->uri = g_strdup(url);
851     uri->start = gtk_stext_get_point(text);
852     gtk_stext_insert(text, textview->msgfont, link_color, NULL, buf,
853                     strlen(buf));
854     uri->end = gtk_stext_get_point(text);
855     textview->uri_list = g_slist_append(textview->uri_list, uri);
856 }
857
858 static void textview_write_line(TextView *textview, const gchar *str,
859                                 CodeConverter *conv)
860 {
861         GtkSText *text = GTK_STEXT(textview->text);
862         gchar buf[BUFFSIZE];
863         GdkColor *fg_color;
864         gint quotelevel = -1;
865
866         if (!conv)
867                 strncpy2(buf, str, sizeof(buf));
868         else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
869                 gtk_stext_insert(text, textview->msgfont,
870                                 prefs_common.enable_color
871                                 ? &error_color : NULL, NULL,
872                                 "*** Warning: code conversion failed ***\n",
873                                 -1);
874                 return;
875         }
876
877         strcrchomp(buf);
878         if (prefs_common.conv_mb_alnum) conv_mb_alnum(buf);
879         fg_color = NULL;
880
881         /* change color of quotation
882            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
883            Up to 3 levels of quotations are detected, and each
884            level is colored using a different color. */
885         if (prefs_common.enable_color && strchr(buf, '>')) {
886                 quotelevel = get_quote_level(buf);
887
888                 /* set up the correct foreground color */
889                 if (quotelevel > 2) {
890                         /* recycle colors */
891                         if (prefs_common.recycle_quote_colors)
892                                 quotelevel %= 3;
893                         else
894                                 quotelevel = 2;
895                 }
896         }
897
898         if (quotelevel == -1)
899                 fg_color = NULL;
900         else
901                 fg_color = &quote_colors[quotelevel];
902
903         if (prefs_common.head_space && spacingfont && buf[0] != '\n')
904                 gtk_stext_insert(text, spacingfont, NULL, NULL, " ", 1);
905
906         if (prefs_common.enable_color)
907                 textview_make_clickable_parts(textview, textview->msgfont,
908                                               fg_color, &uri_color, buf);
909         else
910                 textview_make_clickable_parts(textview, textview->msgfont,
911                                               fg_color, NULL, buf);
912 }
913
914 void textview_clear(TextView *textview)
915 {
916         GtkSText *text = GTK_STEXT(textview->text);
917
918         gtk_stext_freeze(text);
919         gtk_stext_set_point(text, 0);
920         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
921         gtk_stext_thaw(text);
922
923         textview_uri_list_remove_all(textview->uri_list);
924         textview->uri_list = NULL;
925 }
926
927 void textview_destroy(TextView *textview)
928 {
929         textview_uri_list_remove_all(textview->uri_list);
930         textview->uri_list = NULL;
931
932         if (!textview->scrolledwin_sb->parent)
933                 gtk_widget_destroy(textview->scrolledwin_sb);
934         if (!textview->scrolledwin_mb->parent)
935                 gtk_widget_destroy(textview->scrolledwin_mb);
936
937         if (textview->msgfont) {
938                 textview->msgfont->ascent = textview->prev_ascent;
939                 textview->msgfont->descent = textview->prev_descent;
940                 gdk_font_unref(textview->msgfont);
941         }
942         if (textview->boldfont)
943                 gdk_font_unref(textview->boldfont);
944
945         g_free(textview);
946 }
947
948 void textview_set_font(TextView *textview, const gchar *codeset)
949 {
950         gboolean use_fontset = TRUE;
951
952         /* In multi-byte mode, GtkSText can't display 8bit characters
953            correctly, so it must be single-byte mode. */
954         if (MB_CUR_MAX > 1) {
955                 if (codeset) {
956                         if (!g_strncasecmp(codeset, "ISO-8859-", 9) ||
957                             !g_strcasecmp(codeset, "BALTIC"))
958                                 use_fontset = FALSE;
959                         else if (conv_get_current_charset() != C_EUC_JP &&
960                                  (!g_strncasecmp(codeset, "KOI8-", 5) ||
961                                   !g_strncasecmp(codeset, "CP", 2)    ||
962                                   !g_strncasecmp(codeset, "WINDOWS-", 8)))
963                                 use_fontset = FALSE;
964                 }
965         } else
966                 use_fontset = FALSE;
967
968         if (textview->text_is_mb && !use_fontset) {
969                 GtkWidget *parent;
970
971                 parent = textview->scrolledwin_mb->parent;
972                 gtkut_container_remove(GTK_CONTAINER(parent),
973                                        textview->scrolledwin_mb);
974                 gtk_container_add(GTK_CONTAINER(parent),
975                                   textview->scrolledwin_sb);
976
977                 textview->text = textview->text_sb;
978                 textview->text_is_mb = FALSE;
979         } else if (!textview->text_is_mb && use_fontset) {
980                 GtkWidget *parent;
981
982                 parent = textview->scrolledwin_sb->parent;
983                 gtkut_container_remove(GTK_CONTAINER(parent),
984                                        textview->scrolledwin_sb);
985                 gtk_container_add(GTK_CONTAINER(parent),
986                                   textview->scrolledwin_mb);
987
988                 textview->text = textview->text_mb;
989                 textview->text_is_mb = TRUE;
990         }
991
992         if (prefs_common.textfont) {
993                 if (textview->msgfont) {
994                         textview->msgfont->ascent = textview->prev_ascent;
995                         textview->msgfont->descent = textview->prev_descent;
996                         gdk_font_unref(textview->msgfont);
997                         textview->msgfont = NULL;
998                 }
999                 if (use_fontset)
1000                         textview->msgfont =
1001                                 gdk_fontset_load(prefs_common.textfont);
1002                 else {
1003                         if (MB_CUR_MAX > 1) {
1004                                 FONT_LOAD(textview->msgfont,
1005                                           "-*-courier-medium-r-normal--14-*-*-*-*-*-iso8859-1");
1006                         } else {
1007                                 FONT_LOAD(textview->msgfont,
1008                                           prefs_common.textfont);
1009                         }
1010                 }
1011
1012                 if (textview->msgfont) {
1013                         gint ascent, descent;
1014
1015                         textview->prev_ascent = textview->msgfont->ascent;
1016                         textview->prev_descent = textview->msgfont->descent;
1017                         descent = prefs_common.line_space / 2;
1018                         ascent  = prefs_common.line_space - descent;
1019                         textview->msgfont->ascent  += ascent;
1020                         textview->msgfont->descent += descent;
1021                 }
1022         }
1023
1024         if (!textview->boldfont)
1025                 FONT_LOAD(textview->boldfont, BOLD_FONT);
1026         if (!spacingfont)
1027                 spacingfont = gdk_font_load("-*-*-medium-r-normal--6-*");
1028 }
1029
1030 enum
1031 {
1032         H_DATE          = 0,
1033         H_FROM          = 1,
1034         H_TO            = 2,
1035         H_NEWSGROUPS    = 3,
1036         H_SUBJECT       = 4,
1037         H_CC            = 5,
1038         H_REPLY_TO      = 6,
1039         H_FOLLOWUP_TO   = 7,
1040         H_X_MAILER      = 8,
1041         H_X_NEWSREADER  = 9,
1042         H_USER_AGENT    = 10,
1043         H_ORGANIZATION  = 11,
1044 };
1045
1046 void textview_set_position(TextView *textview, gint pos)
1047 {
1048         if (pos < 0) {
1049                 textview->cur_pos =
1050                         gtk_stext_get_length(GTK_STEXT(textview->text));
1051         } else {
1052                 textview->cur_pos = pos;
1053         }
1054 }
1055
1056 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1057 {
1058         gchar buf[BUFFSIZE];
1059         GPtrArray *headers, *sorted_headers;
1060         GSList *disphdr_list;
1061         Header *header;
1062         gint i;
1063
1064         g_return_val_if_fail(fp != NULL, NULL);
1065
1066         if (!prefs_common.display_header) {
1067                 while (fgets(buf, sizeof(buf), fp) != NULL)
1068                         if (buf[0] == '\r' || buf[0] == '\n') break;
1069                 return NULL;
1070         }
1071
1072         headers = procheader_get_header_array_asis(fp);
1073
1074         sorted_headers = g_ptr_array_new();
1075
1076         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1077              disphdr_list = disphdr_list->next) {
1078                 DisplayHeaderProp *dp =
1079                         (DisplayHeaderProp *)disphdr_list->data;
1080
1081                 for (i = 0; i < headers->len; i++) {
1082                         header = g_ptr_array_index(headers, i);
1083
1084                         if (procheader_headername_equal(header->name,
1085                                                         dp->name)) {
1086                                 if (dp->hidden)
1087                                         procheader_header_free(header);
1088                                 else
1089                                         g_ptr_array_add(sorted_headers, header);
1090
1091                                 g_ptr_array_remove_index(headers, i);
1092                                 i--;
1093                         }
1094                 }
1095         }
1096
1097         if (prefs_common.show_other_header) {
1098                 for (i = 0; i < headers->len; i++) {
1099                         header = g_ptr_array_index(headers, i);
1100                         g_ptr_array_add(sorted_headers, header);
1101                 }
1102         }
1103
1104         g_ptr_array_free(headers, FALSE);
1105
1106         return sorted_headers;
1107 }
1108
1109 static void textview_show_header(TextView *textview, GPtrArray *headers)
1110 {
1111         GtkSText *text = GTK_STEXT(textview->text);
1112         Header *header;
1113         gint i;
1114
1115         g_return_if_fail(headers != NULL);
1116
1117         gtk_stext_freeze(text);
1118
1119         for (i = 0; i < headers->len; i++) {
1120                 header = g_ptr_array_index(headers, i);
1121                 g_return_if_fail(header->name != NULL);
1122
1123                 gtk_stext_insert(text, textview->boldfont, NULL, NULL,
1124                                 header->name, -1);
1125                 if (header->name[strlen(header->name) - 1] != ' ')
1126                         gtk_stext_insert(text, textview->boldfont,
1127                                         NULL, NULL, " ", 1);
1128
1129                 if (procheader_headername_equal(header->name, "Subject") ||
1130                     procheader_headername_equal(header->name, "From")    ||
1131                     procheader_headername_equal(header->name, "To")      ||
1132                     procheader_headername_equal(header->name, "Cc"))
1133                         unfold_line(header->body);
1134
1135                 if (prefs_common.enable_color &&
1136                     (procheader_headername_equal(header->name, "X-Mailer") ||
1137                      procheader_headername_equal(header->name,
1138                                                  "X-Newsreader")) &&
1139                     strstr(header->body, "Sylpheed") != NULL)
1140                         gtk_stext_insert(text, NULL, &emphasis_color, NULL,
1141                                         header->body, -1);
1142                 else if (prefs_common.enable_color) {
1143                         textview_make_clickable_parts(textview,
1144                                                       NULL, NULL, &uri_color,
1145                                                       header->body);
1146                 } else {
1147                         textview_make_clickable_parts(textview,
1148                                                       NULL, NULL, NULL,
1149                                                       header->body);
1150                 }
1151                 gtk_stext_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1152         }
1153
1154         gtk_stext_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1155         gtk_stext_thaw(text);
1156         textview->body_pos = gtk_stext_get_length(text);
1157 }
1158
1159 gboolean textview_search_string(TextView *textview, const gchar *str,
1160                                 gboolean case_sens)
1161 {
1162         GtkSText *text = GTK_STEXT(textview->text);
1163         gint pos;
1164         wchar_t *wcs;
1165         gint len;
1166         gint text_len;
1167         gboolean found = FALSE;
1168
1169         g_return_val_if_fail(str != NULL, FALSE);
1170
1171         wcs = strdup_mbstowcs(str);
1172         g_return_val_if_fail(wcs != NULL, FALSE);
1173         len = wcslen(wcs);
1174         pos = textview->cur_pos;
1175         if (pos < textview->body_pos)
1176                 pos = textview->body_pos;
1177         text_len = gtk_stext_get_length(text);
1178         if (text_len - pos < len) {
1179                 g_free(wcs);
1180                 return FALSE;
1181         }
1182
1183         for (; pos < text_len; pos++) {
1184                 if (text_len - pos < len) break;
1185                 if (gtkut_stext_match_string(text, pos, wcs, len, case_sens)
1186                     == TRUE) {
1187                         gtk_editable_set_position(GTK_EDITABLE(text),
1188                                                   pos + len);
1189                         gtk_editable_select_region(GTK_EDITABLE(text),
1190                                                    pos, pos + len);
1191                         textview_set_position(textview, pos + len);
1192                         found = TRUE;
1193                         break;
1194                 }
1195                 if (text_len - pos == len) break;
1196         }
1197
1198         g_free(wcs);
1199         return found;
1200 }
1201
1202 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1203                                          gboolean case_sens)
1204 {
1205         GtkSText *text = GTK_STEXT(textview->text);
1206         gint pos;
1207         wchar_t *wcs;
1208         gint len;
1209         gint text_len;
1210         gboolean found = FALSE;
1211
1212         g_return_val_if_fail(str != NULL, FALSE);
1213
1214         wcs = strdup_mbstowcs(str);
1215         g_return_val_if_fail(wcs != NULL, FALSE);
1216         len = wcslen(wcs);
1217         pos = textview->cur_pos;
1218         text_len = gtk_stext_get_length(text);
1219         if (text_len - textview->body_pos < len) {
1220                 g_free(wcs);
1221                 return FALSE;
1222         }
1223         if (pos <= textview->body_pos || text_len - pos < len)
1224                 pos = text_len - len;
1225
1226         for (; pos >= textview->body_pos; pos--) {
1227                 if (gtkut_stext_match_string(text, pos, wcs, len, case_sens)
1228                     == TRUE) {
1229                         gtk_editable_set_position(GTK_EDITABLE(text), pos);
1230                         gtk_editable_select_region(GTK_EDITABLE(text),
1231                                                    pos, pos + len);
1232                         textview_set_position(textview, pos - 1);
1233                         found = TRUE;
1234                         break;
1235                 }
1236                 if (pos == textview->body_pos) break;
1237         }
1238
1239         g_free(wcs);
1240         return found;
1241 }
1242
1243 void textview_scroll_one_line(TextView *textview, gboolean up)
1244 {
1245         GtkSText *text = GTK_STEXT(textview->text);
1246         gfloat upper;
1247
1248         if (prefs_common.enable_smooth_scroll) {
1249                 textview_smooth_scroll_one_line(textview, up);
1250                 return;
1251         }
1252
1253         if (!up) {
1254                 upper = text->vadj->upper - text->vadj->page_size;
1255                 if (text->vadj->value < upper) {
1256                         text->vadj->value +=
1257                                 text->vadj->step_increment * 4;
1258                         text->vadj->value =
1259                                 MIN(text->vadj->value, upper);
1260                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1261                                                 "value_changed");
1262                 }
1263         } else {
1264                 if (text->vadj->value > 0.0) {
1265                         text->vadj->value -=
1266                                 text->vadj->step_increment * 4;
1267                         text->vadj->value =
1268                                 MAX(text->vadj->value, 0.0);
1269                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1270                                                 "value_changed");
1271                 }
1272         }
1273 }
1274
1275 gboolean textview_scroll_page(TextView *textview, gboolean up)
1276 {
1277         GtkSText *text = GTK_STEXT(textview->text);
1278         gfloat upper;
1279         gfloat page_incr;
1280
1281         if (prefs_common.enable_smooth_scroll)
1282                 return textview_smooth_scroll_page(textview, up);
1283
1284         if (prefs_common.scroll_halfpage)
1285                 page_incr = text->vadj->page_increment / 2;
1286         else
1287                 page_incr = text->vadj->page_increment;
1288
1289         if (!up) {
1290                 upper = text->vadj->upper - text->vadj->page_size;
1291                 if (text->vadj->value < upper) {
1292                         text->vadj->value += page_incr;
1293                         text->vadj->value = MIN(text->vadj->value, upper);
1294                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1295                                                 "value_changed");
1296                 } else
1297                         return FALSE;
1298         } else {
1299                 if (text->vadj->value > 0.0) {
1300                         text->vadj->value -= page_incr;
1301                         text->vadj->value = MAX(text->vadj->value, 0.0);
1302                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1303                                                 "value_changed");
1304                 } else
1305                         return FALSE;
1306         }
1307
1308         return TRUE;
1309 }
1310
1311 static void textview_smooth_scroll_do(TextView *textview,
1312                                       gfloat old_value, gfloat last_value,
1313                                       gint step)
1314 {
1315         GtkSText *text = GTK_STEXT(textview->text);
1316         gint change_value;
1317         gboolean up;
1318         gint i;
1319
1320         if (old_value < last_value) {
1321                 change_value = last_value - old_value;
1322                 up = FALSE;
1323         } else {
1324                 change_value = old_value - last_value;
1325                 up = TRUE;
1326         }
1327
1328         gdk_key_repeat_disable();
1329
1330         for (i = step; i <= change_value; i += step) {
1331                 text->vadj->value = old_value + (up ? -i : i);
1332                 gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1333                                         "value_changed");
1334         }
1335
1336         text->vadj->value = last_value;
1337         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj), "value_changed");
1338
1339         gdk_key_repeat_restore();
1340 }
1341
1342 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1343 {
1344         GtkSText *text = GTK_STEXT(textview->text);
1345         gfloat upper;
1346         gfloat old_value;
1347         gfloat last_value;
1348
1349         if (!up) {
1350                 upper = text->vadj->upper - text->vadj->page_size;
1351                 if (text->vadj->value < upper) {
1352                         old_value = text->vadj->value;
1353                         last_value = text->vadj->value +
1354                                 text->vadj->step_increment * 4;
1355                         last_value = MIN(last_value, upper);
1356
1357                         textview_smooth_scroll_do(textview, old_value,
1358                                                   last_value,
1359                                                   prefs_common.scroll_step);
1360                 }
1361         } else {
1362                 if (text->vadj->value > 0.0) {
1363                         old_value = text->vadj->value;
1364                         last_value = text->vadj->value -
1365                                 text->vadj->step_increment * 4;
1366                         last_value = MAX(last_value, 0.0);
1367
1368                         textview_smooth_scroll_do(textview, old_value,
1369                                                   last_value,
1370                                                   prefs_common.scroll_step);
1371                 }
1372         }
1373 }
1374
1375 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1376 {
1377         GtkSText *text = GTK_STEXT(textview->text);
1378         gfloat upper;
1379         gfloat page_incr;
1380         gfloat old_value;
1381         gfloat last_value;
1382
1383         if (prefs_common.scroll_halfpage)
1384                 page_incr = text->vadj->page_increment / 2;
1385         else
1386                 page_incr = text->vadj->page_increment;
1387
1388         if (!up) {
1389                 upper = text->vadj->upper - text->vadj->page_size;
1390                 if (text->vadj->value < upper) {
1391                         old_value = text->vadj->value;
1392                         last_value = text->vadj->value + page_incr;
1393                         last_value = MIN(last_value, upper);
1394
1395                         textview_smooth_scroll_do(textview, old_value,
1396                                                   last_value,
1397                                                   prefs_common.scroll_step);
1398                 } else
1399                         return FALSE;
1400         } else {
1401                 if (text->vadj->value > 0.0) {
1402                         old_value = text->vadj->value;
1403                         last_value = text->vadj->value - page_incr;
1404                         last_value = MAX(last_value, 0.0);
1405
1406                         textview_smooth_scroll_do(textview, old_value,
1407                                                   last_value,
1408                                                   prefs_common.scroll_step);
1409                 } else
1410                         return FALSE;
1411         }
1412
1413         return TRUE;
1414 }
1415
1416 static void textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1417                                  TextView *textview)
1418 {
1419         SummaryView *summaryview = NULL;
1420
1421         if (!event) return;
1422         if (textview->messageview->mainwin)
1423                 summaryview = textview->messageview->mainwin->summaryview;
1424
1425         switch (event->keyval) {
1426         case GDK_Tab:
1427         case GDK_Home:
1428         case GDK_Left:
1429         case GDK_Up:
1430         case GDK_Right:
1431         case GDK_Down:
1432         case GDK_Page_Up:
1433         case GDK_Page_Down:
1434         case GDK_End:
1435         case GDK_Control_L:
1436         case GDK_Control_R:
1437                 break;
1438         case GDK_space:
1439                 if (summaryview)
1440                         summary_pass_key_press_event(summaryview, event);
1441                 else
1442                         textview_scroll_page(textview, FALSE);
1443                 break;
1444         case GDK_BackSpace:
1445                 textview_scroll_page(textview, TRUE);
1446                 break;
1447         case GDK_Return:
1448                 textview_scroll_one_line(textview,
1449                                          (event->state & GDK_MOD1_MASK) != 0);
1450                 break;
1451         default:
1452                 if (summaryview)
1453                         summary_pass_key_press_event(summaryview, event);
1454                 break;
1455         }
1456 }
1457
1458 static gint textview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1459                                     TextView *textview)
1460 {
1461         if (event)
1462                 textview->last_buttonpress = event->type;
1463         return FALSE;
1464 }
1465
1466 static gint textview_button_released(GtkWidget *widget, GdkEventButton *event,
1467                                     TextView *textview)
1468 {
1469         textview->cur_pos = 
1470                 gtk_editable_get_position(GTK_EDITABLE(textview->text));
1471
1472         if (event && 
1473             ((event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS)
1474              || event->button == 2 || event->button == 3)) {
1475                 GSList *cur;
1476
1477                 /* double click seems to set the cursor after the current
1478                  * word. The cursor position needs fixing, otherwise the
1479                  * last word of a clickable zone will not work */
1480                 if (event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS) {
1481                         textview->cur_pos--;
1482                 }
1483
1484                 for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1485                         RemoteURI *uri = (RemoteURI *)cur->data;
1486
1487                         if (textview->cur_pos >= uri->start &&
1488                             textview->cur_pos <  uri->end) {
1489                                 if (!g_strncasecmp(uri->uri, "mailto:", 7)) {
1490                                         if (event->button == 3) {
1491                                                 gchar *fromname, *fromaddress;
1492                                                 GdkEventButton tmpev;   
1493                                                 
1494                                                 /* extract url */
1495                                                 fromaddress = g_strdup(uri->uri + 7);
1496                                                 /* Hiroyuki: please put this function in utils.c! */
1497                                                 fromname = procheader_get_fromname(fromaddress);
1498                                                 extract_address(fromaddress);
1499                                                 g_message("adding from textview %s <%s>", fromname, fromaddress);
1500                                                 /* Add to address book - Match */
1501                                                 addressbook_add_contact( fromname, fromaddress, NULL );
1502                                                 
1503                                                 g_free(fromaddress);
1504                                                 g_free(fromname);
1505                                         } else {
1506                                                 PrefsAccount *account = NULL;
1507                                                 FolderItem   *folder_item;
1508
1509                                                 if (textview->messageview && textview->messageview->mainwin 
1510                                                 &&  textview->messageview->mainwin->summaryview 
1511                                                 &&  textview->messageview->mainwin->summaryview->folder_item) {
1512                                                         folder_item = textview->messageview->mainwin->summaryview->folder_item;
1513                                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
1514                                                                 account = account_find_from_id(folder_item->prefs->default_account);
1515                                                 }
1516                                                 compose_new_with_recipient
1517                                                         (account, uri->uri + 7);
1518                                         }
1519                                 } else {
1520                                         open_uri(uri->uri,
1521                                                  prefs_common.uri_cmd);
1522                                 }
1523                         }
1524                 }
1525         }
1526         if (event)
1527                 textview->last_buttonpress = event->type;
1528         return FALSE;
1529 }
1530
1531 static void textview_uri_list_remove_all(GSList *uri_list)
1532 {
1533         GSList *cur;
1534
1535         for (cur = uri_list; cur != NULL; cur = cur->next) {
1536                 if (cur->data) {
1537                         g_free(((RemoteURI *)cur->data)->uri);
1538                         g_free(cur->data);
1539                 }
1540         }
1541
1542         g_slist_free(uri_list);
1543 }