8ef900501b7138ed2cb2cbe29e3e33426a83cb53
[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 gint 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 #if 0
386         tmpfp = procmime_decode_content(NULL, fp, mimeinfo);
387
388         if (tmpfp) {
389                 if (mimeinfo->mime_type == MIME_TEXT_HTML)
390                         textview_show_html(textview, tmpfp, conv);
391                 else if (mimeinfo->mime_type == MIME_TEXT_ENRICHED)
392                         textview_show_ertf(textview, tmpfp, conv);
393                 else
394                         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
395                                 textview_write_line(textview, buf, conv);
396                 fclose(tmpfp);
397         }
398 #else
399         tmpfp = procmime_get_text_content(mimeinfo, fp);
400
401         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
402                 textview_write_line(textview, buf, conv);
403
404         fclose(tmpfp);
405 #endif
406
407         conv_code_converter_destroy(conv);
408
409         gtk_stext_thaw(text);
410 }
411
412 #define TEXT_INSERT(str) \
413         gtk_stext_insert(text, textview->msgfont, NULL, NULL, str, -1)
414
415 void textview_show_mime_part(TextView *textview, MimeInfo *partinfo)
416 {
417         GtkSText *text;
418
419         if (!partinfo) return;
420
421         textview_set_font(textview, NULL);
422         text = GTK_STEXT(textview->text);
423         textview_clear(textview);
424
425         gtk_stext_freeze(text);
426
427         TEXT_INSERT(_("To save this part, pop up the context menu with "));
428         TEXT_INSERT(_("right click and select `Save as...', "));
429         TEXT_INSERT(_("or press `y' key.\n\n"));
430
431         TEXT_INSERT(_("To display this part as a text message, select "));
432         TEXT_INSERT(_("`Display as text', or press `t' key.\n\n"));
433
434         TEXT_INSERT(_("To open this part with external program, select "));
435         TEXT_INSERT(_("`Open' or `Open with...', "));
436         TEXT_INSERT(_("or double-click, or click the center button, "));
437         TEXT_INSERT(_("or press `l' key."));
438
439         gtk_stext_thaw(text);
440 }
441
442 #if USE_GPGME
443 void textview_show_signature_part(TextView *textview, MimeInfo *partinfo)
444 {
445         GtkSText *text;
446
447         if (!partinfo) return;
448
449         textview_set_font(textview, NULL);
450         text = GTK_STEXT(textview->text);
451         textview_clear(textview);
452
453         gtk_stext_freeze(text);
454
455         if (partinfo->sigstatus_full == NULL) {
456                 TEXT_INSERT(_("This signature has not been checked yet.\n"));
457                 TEXT_INSERT(_("To check it, pop up the context menu with\n"));
458                 TEXT_INSERT(_("right click and select `Check signature'.\n"));
459         } else {
460                 TEXT_INSERT(partinfo->sigstatus_full);
461         }
462
463         gtk_stext_thaw(text);
464 }
465 #endif /* USE_GPGME */
466
467 #undef TEXT_INSERT
468
469 static void textview_show_html(TextView *textview, FILE *fp,
470                                CodeConverter *conv)
471 {
472         HTMLParser *parser;
473         gchar *str;
474         gchar* url = NULL;
475
476         parser = html_parser_new(fp, conv);
477         g_return_if_fail(parser != NULL);
478
479         while ((str = html_parse(parser)) != NULL) {
480                 if (parser->state == HTML_HREF) {
481                         /* first time : get and copy the URL */
482                         if (url == NULL) {
483                                 /* ALF - the sylpheed html parser returns an empty string,
484                                  * if still inside an <a>, but already parsed past HREF */
485                                 str = strtok(str, " ");
486                                 if (str) { 
487                                         url = strdup(str);
488                                         /* the URL may (or not) be followed by the
489                                          * referenced text */
490                                         str = strtok(NULL, "");
491                                 }       
492                         }
493                         if (str != NULL) {
494                                 textview_write_link(textview, url, str, NULL);
495                         }
496                 } else {
497                         if (url != NULL) {
498                                 free(url);
499                                 url = NULL;
500                         }
501                         textview_write_line(textview, str, NULL);
502                 }
503         }
504         html_parser_destroy(parser);
505 }
506
507 static void textview_show_ertf(TextView *textview, FILE *fp,
508                                CodeConverter *conv)
509 {
510         ERTFParser *parser;
511         gchar *str;
512         gchar* url = NULL;
513
514         parser = ertf_parser_new(fp, conv);
515         g_return_if_fail(parser != NULL);
516
517         while ((str = ertf_parse(parser)) != NULL) {
518                 textview_write_line(textview, str, NULL);
519         }
520         ertf_parser_destroy(parser);
521 }
522
523 /* get_uri_part() - retrieves a URI starting from scanpos.
524                     Returns TRUE if succesful */
525 static gboolean get_uri_part(const gchar *start, const gchar *scanpos,
526                              const gchar **bp, const gchar **ep)
527 {
528         const gchar *ep_;
529
530         g_return_val_if_fail(start != NULL, FALSE);
531         g_return_val_if_fail(scanpos != NULL, FALSE);
532         g_return_val_if_fail(bp != NULL, FALSE);
533         g_return_val_if_fail(ep != NULL, FALSE);
534
535         *bp = scanpos;
536
537         /* find end point of URI */
538         for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
539                 if (!isgraph(*ep_) || !isascii(*ep_) || strchr("()<>\"", *ep_))
540                         break;
541         }
542
543         /* no punctuation at end of string */
544
545         /* FIXME: this stripping of trailing punctuations may bite with other URIs.
546          * should pass some URI type to this function and decide on that whether
547          * to perform punctuation stripping */
548
549 #define IS_REAL_PUNCT(ch)       (ispunct(ch) && ((ch) != '/')) 
550
551         for (; ep_ - 1 > scanpos + 1 && IS_REAL_PUNCT(*(ep_ - 1)); ep_--)
552                 ;
553
554 #undef IS_REAL_PUNCT
555
556         *ep = ep_;
557
558         return TRUE;            
559 }
560
561 static gchar *make_uri_string(const gchar *bp, const gchar *ep)
562 {
563         return g_strndup(bp, ep - bp);
564 }
565
566 /* valid mail address characters */
567 #define IS_RFC822_CHAR(ch) \
568         (isascii(ch) && \
569          (ch) > 32   && \
570          (ch) != 127 && \
571          !isspace(ch) && \
572          !strchr("()<>\"", (ch)))
573
574 /* alphabet and number within 7bit ASCII */
575 #define IS_ASCII_ALNUM(ch)      (isascii(ch) && isalnum(ch))
576 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
577
578 /* get_email_part() - retrieves an email address. Returns TRUE if succesful */
579 static gboolean get_email_part(const gchar *start, const gchar *scanpos,
580                                const gchar **bp, const gchar **ep)
581 {
582         /* more complex than the uri part because we need to scan back and forward starting from
583          * the scan position. */
584         gboolean result = FALSE;
585         const gchar *bp_ = NULL;
586         const gchar *ep_ = NULL;
587
588         /* the informative part of the email address (describing the name
589          * of the email address owner) may contain quoted parts. the
590          * closure stack stores the last encountered quotes. */
591         gchar closure_stack[128];
592         gchar *ptr = closure_stack;
593
594         g_return_val_if_fail(start != NULL, FALSE);
595         g_return_val_if_fail(scanpos != NULL, FALSE);
596         g_return_val_if_fail(bp != NULL, FALSE);
597         g_return_val_if_fail(ep != NULL, FALSE);
598
599         /* scan start of address */
600         for (bp_ = scanpos - 1; bp_ >= start && IS_RFC822_CHAR(*bp_); bp_--)
601                 ;
602
603         /* TODO: should start with an alnum? */
604         bp_++;
605         for (; bp_ < scanpos && !IS_ASCII_ALNUM(*bp_); bp_++)
606                 ;
607
608         if (bp_ != scanpos) {
609                 /* scan end of address */
610                 for (ep_ = scanpos + 1; *ep_ && IS_RFC822_CHAR(*ep_); ep_++)
611                         ;
612
613                 /* TODO: really should terminate with an alnum? */
614                 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*ep_); --ep_)
615                         ;
616                 ep_++;
617
618                 if (ep_ > scanpos + 1) {
619                         *ep = ep_;
620                         *bp = bp_;
621                         result = TRUE;
622                 }
623         }
624
625         if (!result) return FALSE;
626
627         /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
628         if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_)) 
629                 return FALSE;
630
631         /* see if this is <bracketed>; in this case we also scan for the informative part. */
632         if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
633                 return TRUE;
634
635 #define FULL_STACK()    ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
636 #define IN_STACK()      (ptr > closure_stack)
637 /* has underrun check */
638 #define POP_STACK()     if(IN_STACK()) --ptr
639 /* has overrun check */
640 #define PUSH_STACK(c)   if(!FULL_STACK()) *ptr++ = (c); else return TRUE
641 /* has underrun check */
642 #define PEEK_STACK()    (IN_STACK() ? *(ptr - 1) : 0)
643
644         ep_++;
645
646         /* scan for the informative part. */
647         for (bp_ -= 2; bp_ >= start; bp_--) {
648                 /* if closure on the stack keep scanning */
649                 if (PEEK_STACK() == *bp_) {
650                         POP_STACK();
651                         continue;
652                 }
653                 if (*bp_ == '\'' || *bp_ == '"') {
654                         PUSH_STACK(*bp_);
655                         continue;
656                 }
657
658                 /* if nothing in the closure stack, do the special conditions
659                  * the following if..else expression simply checks whether 
660                  * a token is acceptable. if not acceptable, the clause
661                  * should terminate the loop with a 'break' */
662                 if (!PEEK_STACK()) {
663                         if (*bp_ == '-'
664                         && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
665                         && (((bp_ + 1) < ep_)    && isalnum(*(bp_ + 1)))) {
666                                 /* hyphens are allowed, but only in
667                                    between alnums */
668                         } else if (!ispunct(*bp_)) {
669                                 /* but anything not being a punctiation
670                                    is ok */
671                         } else {
672                                 break; /* anything else is rejected */
673                         }
674                 }
675         }
676
677         bp_++;
678
679 #undef PEEK_STACK
680 #undef PUSH_STACK
681 #undef POP_STACK
682 #undef IN_STACK
683 #undef FULL_STACK
684
685         /* scan forward (should start with an alnum) */
686         for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
687                 ;
688
689         *ep = ep_;
690         *bp = bp_;
691
692         return result;
693 }
694
695 #undef IS_QUOTE
696 #undef IS_RFC822_CHAR
697
698 static gchar *make_email_string(const gchar *bp, const gchar *ep)
699 {
700         /* returns a mailto: URI; mailto: is also used to detect the
701          * uri type later on in the button_pressed signal handler */
702         gchar *tmp;
703         gchar *result;
704
705         tmp = g_strndup(bp, ep - bp);
706         result = g_strconcat("mailto:", tmp, NULL);
707         g_free(tmp);
708
709         return result;
710 }
711
712 #define ADD_TXT_POS(bp_, ep_, pti_) \
713         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
714                 last = last->next; \
715                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
716                 last->next = NULL; \
717         } else { \
718                 g_warning("alloc error scanning URIs\n"); \
719                 gtk_stext_insert(text, textview->msgfont, fg_color, NULL, \
720                                 linebuf, -1); \
721                 return; \
722         }
723
724 /* textview_make_clickable_parts() - colorizes clickable parts */
725 static void textview_make_clickable_parts(TextView *textview,
726                                           GdkFont *font,
727                                           GdkColor *fg_color,
728                                           GdkColor *uri_color,
729                                           const gchar *linebuf)
730 {
731         /* parse table - in order of priority */
732         struct table {
733                 const gchar *needle; /* token */
734
735                 /* token search function */
736                 gchar    *(*search)     (const gchar *haystack,
737                                          const gchar *needle);
738                 /* part parsing function */
739                 gboolean  (*parse)      (const gchar *start,
740                                          const gchar *scanpos,
741                                          const gchar **bp_,
742                                          const gchar **ep_);
743                 /* part to URI function */
744                 gchar    *(*build_uri)  (const gchar *bp,
745                                          const gchar *ep);
746         };
747
748         static struct table parser[] = {
749                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
750                 {"https://", strcasestr, get_uri_part,   make_uri_string},
751                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
752                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
753                 {"@",        strcasestr, get_email_part, make_email_string}
754         };
755         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
756
757         gint  n;
758         const gchar *walk, *bp, *ep;
759
760         struct txtpos {
761                 const gchar     *bp, *ep;       /* text position */
762                 gint             pti;           /* index in parse table */
763                 struct txtpos   *next;          /* next */
764         } head = {NULL, NULL, 0,  NULL}, *last = &head;
765
766         GtkSText *text = GTK_STEXT(textview->text);
767
768         /* parse for clickable parts, and build a list of begin and end positions  */
769         for (walk = linebuf, n = 0;;) {
770                 gint last_index = PARSE_ELEMS;
771                 gchar *scanpos = NULL;
772
773                 /* FIXME: this looks phony. scanning for anything in the parse table */
774                 for (n = 0; n < PARSE_ELEMS; n++) {
775                         gchar *tmp;
776
777                         tmp = parser[n].search(walk, parser[n].needle);
778                         if (tmp) {
779                                 if (scanpos == NULL || tmp < scanpos) {
780                                         scanpos = tmp;
781                                         last_index = n;
782                                 }
783                         }                                       
784                 }
785
786                 if (scanpos) {
787                         /* check if URI can be parsed */
788                         if (parser[last_index].parse(linebuf, scanpos, &bp, &ep)
789                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
790                                         ADD_TXT_POS(bp, ep, last_index);
791                                         walk = ep;
792                         } else
793                                 walk = scanpos +
794                                         strlen(parser[last_index].needle);
795                 } else
796                         break;
797         }
798
799         /* colorize this line */
800         if (head.next) {
801                 const gchar *normal_text = linebuf;
802
803                 /* insert URIs */
804                 for (last = head.next; last != NULL;
805                      normal_text = last->ep, last = last->next) {
806                         RemoteURI *uri;
807
808                         uri = g_new(RemoteURI, 1);
809                         if (last->bp - normal_text > 0)
810                                 gtk_stext_insert(text, font,
811                                                 fg_color, NULL,
812                                                 normal_text,
813                                                 last->bp - normal_text);
814                         uri->uri = parser[last->pti].build_uri(last->bp,
815                                                                last->ep);
816                         uri->start = gtk_stext_get_point(text);
817                         gtk_stext_insert(text, font, uri_color,
818                                         NULL, last->bp, last->ep - last->bp);
819                         uri->end = gtk_stext_get_point(text);
820                         textview->uri_list =
821                                 g_slist_append(textview->uri_list, uri);
822                 }
823
824                 if (*normal_text)
825                         gtk_stext_insert(text, font, fg_color,
826                                         NULL, normal_text, -1);
827         } else
828                 gtk_stext_insert(text, font, fg_color, NULL, linebuf, -1);
829 }
830
831 #undef ADD_TXT_POS
832
833 /* This function writes str as a double-clickable link with the given url. */ 
834 static void textview_write_link(TextView *textview, const gchar *url,
835                                 const gchar *str, CodeConverter *conv)
836 {
837     GdkColor *link_color = NULL;
838     RemoteURI* uri;
839     GtkSText *text = GTK_STEXT(textview->text);
840     gchar buf[BUFFSIZE];
841
842     /* this part is taken from textview_write_line. Right now the only place
843      * that calls this function passes NULL for conv, but you never know. */
844     if (!conv)
845             strncpy2(buf, str, sizeof(buf));
846     else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
847             gtk_stext_insert(text, textview->msgfont,
848                             prefs_common.enable_color
849                             ? &error_color : NULL, NULL,
850                             "*** Warning: code conversion failed ***\n",
851                             -1);
852             return;
853     }
854
855     /* this part is based on the code in make_clickable_parts */
856     if (prefs_common.enable_color) {
857         link_color = &uri_color;
858     }
859     uri = g_new(RemoteURI, 1);
860     uri->uri = g_strdup(url);
861     uri->start = gtk_stext_get_point(text);
862     gtk_stext_insert(text, textview->msgfont, link_color, NULL, buf,
863                     strlen(buf));
864     uri->end = gtk_stext_get_point(text);
865     textview->uri_list = g_slist_append(textview->uri_list, uri);
866 }
867
868 static void textview_write_line(TextView *textview, const gchar *str,
869                                 CodeConverter *conv)
870 {
871         GtkSText *text = GTK_STEXT(textview->text);
872         gchar buf[BUFFSIZE];
873         GdkColor *fg_color;
874         gint quotelevel = -1;
875
876         if (!conv)
877                 strncpy2(buf, str, sizeof(buf));
878         else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
879                 gtk_stext_insert(text, textview->msgfont,
880                                 prefs_common.enable_color
881                                 ? &error_color : NULL, NULL,
882                                 "*** Warning: code conversion failed ***\n",
883                                 -1);
884                 return;
885         }
886
887         strcrchomp(buf);
888         if (prefs_common.conv_mb_alnum) conv_mb_alnum(buf);
889         fg_color = NULL;
890
891         /* change color of quotation
892            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
893            Up to 3 levels of quotations are detected, and each
894            level is colored using a different color. */
895         if (prefs_common.enable_color && strchr(buf, '>')) {
896                 quotelevel = get_quote_level(buf);
897
898                 /* set up the correct foreground color */
899                 if (quotelevel > 2) {
900                         /* recycle colors */
901                         if (prefs_common.recycle_quote_colors)
902                                 quotelevel %= 3;
903                         else
904                                 quotelevel = 2;
905                 }
906         }
907
908         if (quotelevel == -1)
909                 fg_color = NULL;
910         else
911                 fg_color = &quote_colors[quotelevel];
912
913         if (prefs_common.head_space && spacingfont && buf[0] != '\n')
914                 gtk_stext_insert(text, spacingfont, NULL, NULL, " ", 1);
915
916         if (prefs_common.enable_color)
917                 textview_make_clickable_parts(textview, textview->msgfont,
918                                               fg_color, &uri_color, buf);
919         else
920                 textview_make_clickable_parts(textview, textview->msgfont,
921                                               fg_color, NULL, buf);
922 }
923
924 void textview_clear(TextView *textview)
925 {
926         GtkSText *text = GTK_STEXT(textview->text);
927
928         gtk_stext_freeze(text);
929         gtk_stext_set_point(text, 0);
930         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
931         gtk_stext_thaw(text);
932
933         textview_uri_list_remove_all(textview->uri_list);
934         textview->uri_list = NULL;
935 }
936
937 void textview_destroy(TextView *textview)
938 {
939         textview_uri_list_remove_all(textview->uri_list);
940         textview->uri_list = NULL;
941
942         if (!textview->scrolledwin_sb->parent)
943                 gtk_widget_destroy(textview->scrolledwin_sb);
944         if (!textview->scrolledwin_mb->parent)
945                 gtk_widget_destroy(textview->scrolledwin_mb);
946
947         if (textview->msgfont) {
948                 textview->msgfont->ascent = textview->prev_ascent;
949                 textview->msgfont->descent = textview->prev_descent;
950                 gdk_font_unref(textview->msgfont);
951         }
952         if (textview->boldfont)
953                 gdk_font_unref(textview->boldfont);
954
955         g_free(textview);
956 }
957
958 void textview_set_font(TextView *textview, const gchar *codeset)
959 {
960         gboolean use_fontset = TRUE;
961
962         /* In multi-byte mode, GtkSText can't display 8bit characters
963            correctly, so it must be single-byte mode. */
964         if (MB_CUR_MAX > 1) {
965                 if (codeset) {
966                         if (!g_strncasecmp(codeset, "ISO-8859-", 9) ||
967                             !g_strcasecmp(codeset, "BALTIC"))
968                                 use_fontset = FALSE;
969                         else if (conv_get_current_charset() != C_EUC_JP &&
970                                  (!g_strncasecmp(codeset, "KOI8-", 5) ||
971                                   !g_strncasecmp(codeset, "CP", 2)    ||
972                                   !g_strncasecmp(codeset, "WINDOWS-", 8)))
973                                 use_fontset = FALSE;
974                 }
975         } else
976                 use_fontset = FALSE;
977
978         if (textview->text_is_mb && !use_fontset) {
979                 GtkWidget *parent;
980
981                 parent = textview->scrolledwin_mb->parent;
982                 gtkut_container_remove(GTK_CONTAINER(parent),
983                                        textview->scrolledwin_mb);
984                 gtk_container_add(GTK_CONTAINER(parent),
985                                   textview->scrolledwin_sb);
986
987                 textview->text = textview->text_sb;
988                 textview->text_is_mb = FALSE;
989         } else if (!textview->text_is_mb && use_fontset) {
990                 GtkWidget *parent;
991
992                 parent = textview->scrolledwin_sb->parent;
993                 gtkut_container_remove(GTK_CONTAINER(parent),
994                                        textview->scrolledwin_sb);
995                 gtk_container_add(GTK_CONTAINER(parent),
996                                   textview->scrolledwin_mb);
997
998                 textview->text = textview->text_mb;
999                 textview->text_is_mb = TRUE;
1000         }
1001
1002         if (prefs_common.textfont) {
1003                 if (textview->msgfont) {
1004                         textview->msgfont->ascent = textview->prev_ascent;
1005                         textview->msgfont->descent = textview->prev_descent;
1006                         gdk_font_unref(textview->msgfont);
1007                         textview->msgfont = NULL;
1008                 }
1009                 if (use_fontset)
1010                         textview->msgfont =
1011                                 gdk_fontset_load(prefs_common.textfont);
1012                 else {
1013                         if (MB_CUR_MAX > 1) {
1014                                 FONT_LOAD(textview->msgfont,
1015                                           "-*-courier-medium-r-normal--14-*-*-*-*-*-iso8859-1");
1016                         } else {
1017                                 FONT_LOAD(textview->msgfont,
1018                                           prefs_common.textfont);
1019                         }
1020                 }
1021
1022                 if (textview->msgfont) {
1023                         gint ascent, descent;
1024
1025                         textview->prev_ascent = textview->msgfont->ascent;
1026                         textview->prev_descent = textview->msgfont->descent;
1027                         descent = prefs_common.line_space / 2;
1028                         ascent  = prefs_common.line_space - descent;
1029                         textview->msgfont->ascent  += ascent;
1030                         textview->msgfont->descent += descent;
1031                 }
1032         }
1033
1034         if (!textview->boldfont)
1035                 FONT_LOAD(textview->boldfont, BOLD_FONT);
1036         if (!spacingfont)
1037                 spacingfont = gdk_font_load("-*-*-medium-r-normal--6-*");
1038 }
1039
1040 enum
1041 {
1042         H_DATE          = 0,
1043         H_FROM          = 1,
1044         H_TO            = 2,
1045         H_NEWSGROUPS    = 3,
1046         H_SUBJECT       = 4,
1047         H_CC            = 5,
1048         H_REPLY_TO      = 6,
1049         H_FOLLOWUP_TO   = 7,
1050         H_X_MAILER      = 8,
1051         H_X_NEWSREADER  = 9,
1052         H_USER_AGENT    = 10,
1053         H_ORGANIZATION  = 11,
1054 };
1055
1056 void textview_set_position(TextView *textview, gint pos)
1057 {
1058         if (pos < 0) {
1059                 textview->cur_pos =
1060                         gtk_stext_get_length(GTK_STEXT(textview->text));
1061         } else {
1062                 textview->cur_pos = pos;
1063         }
1064 }
1065
1066 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1067 {
1068         gchar buf[BUFFSIZE];
1069         GPtrArray *headers, *sorted_headers;
1070         GSList *disphdr_list;
1071         Header *header;
1072         gint i;
1073
1074         g_return_val_if_fail(fp != NULL, NULL);
1075
1076         if (!prefs_common.display_header) {
1077                 while (fgets(buf, sizeof(buf), fp) != NULL)
1078                         if (buf[0] == '\r' || buf[0] == '\n') break;
1079                 return NULL;
1080         }
1081
1082         headers = procheader_get_header_array_asis(fp);
1083
1084         sorted_headers = g_ptr_array_new();
1085
1086         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1087              disphdr_list = disphdr_list->next) {
1088                 DisplayHeaderProp *dp =
1089                         (DisplayHeaderProp *)disphdr_list->data;
1090
1091                 for (i = 0; i < headers->len; i++) {
1092                         header = g_ptr_array_index(headers, i);
1093
1094                         if (procheader_headername_equal(header->name,
1095                                                         dp->name)) {
1096                                 if (dp->hidden)
1097                                         procheader_header_free(header);
1098                                 else
1099                                         g_ptr_array_add(sorted_headers, header);
1100
1101                                 g_ptr_array_remove_index(headers, i);
1102                                 i--;
1103                         }
1104                 }
1105         }
1106
1107         if (prefs_common.show_other_header) {
1108                 for (i = 0; i < headers->len; i++) {
1109                         header = g_ptr_array_index(headers, i);
1110                         g_ptr_array_add(sorted_headers, header);
1111                 }
1112         }
1113
1114         g_ptr_array_free(headers, FALSE);
1115
1116         return sorted_headers;
1117 }
1118
1119 static void textview_show_header(TextView *textview, GPtrArray *headers)
1120 {
1121         GtkSText *text = GTK_STEXT(textview->text);
1122         Header *header;
1123         gint i;
1124
1125         g_return_if_fail(headers != NULL);
1126
1127         gtk_stext_freeze(text);
1128
1129         for (i = 0; i < headers->len; i++) {
1130                 header = g_ptr_array_index(headers, i);
1131                 g_return_if_fail(header->name != NULL);
1132
1133                 gtk_stext_insert(text, textview->boldfont, NULL, NULL,
1134                                 header->name, -1);
1135                 if (header->name[strlen(header->name) - 1] != ' ')
1136                         gtk_stext_insert(text, textview->boldfont,
1137                                         NULL, NULL, " ", 1);
1138
1139                 if (procheader_headername_equal(header->name, "Subject") ||
1140                     procheader_headername_equal(header->name, "From")    ||
1141                     procheader_headername_equal(header->name, "To")      ||
1142                     procheader_headername_equal(header->name, "Cc"))
1143                         unfold_line(header->body);
1144
1145                 if (prefs_common.enable_color &&
1146                     (procheader_headername_equal(header->name, "X-Mailer") ||
1147                      procheader_headername_equal(header->name,
1148                                                  "X-Newsreader")) &&
1149                     strstr(header->body, "Sylpheed") != NULL)
1150                         gtk_stext_insert(text, NULL, &emphasis_color, NULL,
1151                                         header->body, -1);
1152                 else if (prefs_common.enable_color) {
1153                         textview_make_clickable_parts(textview,
1154                                                       NULL, NULL, &uri_color,
1155                                                       header->body);
1156                 } else {
1157                         textview_make_clickable_parts(textview,
1158                                                       NULL, NULL, NULL,
1159                                                       header->body);
1160                 }
1161                 gtk_stext_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1162         }
1163
1164         gtk_stext_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1165         gtk_stext_thaw(text);
1166         textview->body_pos = gtk_stext_get_length(text);
1167 }
1168
1169 gboolean textview_search_string(TextView *textview, const gchar *str,
1170                                 gboolean case_sens)
1171 {
1172         GtkSText *text = GTK_STEXT(textview->text);
1173         gint pos;
1174         wchar_t *wcs;
1175         gint len;
1176         gint text_len;
1177         gboolean found = FALSE;
1178
1179         g_return_val_if_fail(str != NULL, FALSE);
1180
1181         wcs = strdup_mbstowcs(str);
1182         g_return_val_if_fail(wcs != NULL, FALSE);
1183         len = wcslen(wcs);
1184         pos = textview->cur_pos;
1185         if (pos < textview->body_pos)
1186                 pos = textview->body_pos;
1187         text_len = gtk_stext_get_length(text);
1188         if (text_len - pos < len) {
1189                 g_free(wcs);
1190                 return FALSE;
1191         }
1192
1193         for (; pos < text_len; pos++) {
1194                 if (text_len - pos < len) break;
1195                 if (gtkut_stext_match_string(text, pos, wcs, len, case_sens)
1196                     == TRUE) {
1197                         gtk_editable_set_position(GTK_EDITABLE(text),
1198                                                   pos + len);
1199                         gtk_editable_select_region(GTK_EDITABLE(text),
1200                                                    pos, pos + len);
1201                         textview_set_position(textview, pos + len);
1202                         found = TRUE;
1203                         break;
1204                 }
1205                 if (text_len - pos == len) break;
1206         }
1207
1208         g_free(wcs);
1209         return found;
1210 }
1211
1212 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1213                                          gboolean case_sens)
1214 {
1215         GtkSText *text = GTK_STEXT(textview->text);
1216         gint pos;
1217         wchar_t *wcs;
1218         gint len;
1219         gint text_len;
1220         gboolean found = FALSE;
1221
1222         g_return_val_if_fail(str != NULL, FALSE);
1223
1224         wcs = strdup_mbstowcs(str);
1225         g_return_val_if_fail(wcs != NULL, FALSE);
1226         len = wcslen(wcs);
1227         pos = textview->cur_pos;
1228         text_len = gtk_stext_get_length(text);
1229         if (text_len - textview->body_pos < len) {
1230                 g_free(wcs);
1231                 return FALSE;
1232         }
1233         if (pos <= textview->body_pos || text_len - pos < len)
1234                 pos = text_len - len;
1235
1236         for (; pos >= textview->body_pos; pos--) {
1237                 if (gtkut_stext_match_string(text, pos, wcs, len, case_sens)
1238                     == TRUE) {
1239                         gtk_editable_set_position(GTK_EDITABLE(text), pos);
1240                         gtk_editable_select_region(GTK_EDITABLE(text),
1241                                                    pos, pos + len);
1242                         textview_set_position(textview, pos - 1);
1243                         found = TRUE;
1244                         break;
1245                 }
1246                 if (pos == textview->body_pos) break;
1247         }
1248
1249         g_free(wcs);
1250         return found;
1251 }
1252
1253 void textview_scroll_one_line(TextView *textview, gboolean up)
1254 {
1255         GtkSText *text = GTK_STEXT(textview->text);
1256         gfloat upper;
1257
1258         if (prefs_common.enable_smooth_scroll) {
1259                 textview_smooth_scroll_one_line(textview, up);
1260                 return;
1261         }
1262
1263         if (!up) {
1264                 upper = text->vadj->upper - text->vadj->page_size;
1265                 if (text->vadj->value < upper) {
1266                         text->vadj->value +=
1267                                 text->vadj->step_increment * 4;
1268                         text->vadj->value =
1269                                 MIN(text->vadj->value, upper);
1270                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1271                                                 "value_changed");
1272                 }
1273         } else {
1274                 if (text->vadj->value > 0.0) {
1275                         text->vadj->value -=
1276                                 text->vadj->step_increment * 4;
1277                         text->vadj->value =
1278                                 MAX(text->vadj->value, 0.0);
1279                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1280                                                 "value_changed");
1281                 }
1282         }
1283 }
1284
1285 gboolean textview_scroll_page(TextView *textview, gboolean up)
1286 {
1287         GtkSText *text = GTK_STEXT(textview->text);
1288         gfloat upper;
1289         gfloat page_incr;
1290
1291         if (prefs_common.enable_smooth_scroll)
1292                 return textview_smooth_scroll_page(textview, up);
1293
1294         if (prefs_common.scroll_halfpage)
1295                 page_incr = text->vadj->page_increment / 2;
1296         else
1297                 page_incr = text->vadj->page_increment;
1298
1299         if (!up) {
1300                 upper = text->vadj->upper - text->vadj->page_size;
1301                 if (text->vadj->value < upper) {
1302                         text->vadj->value += page_incr;
1303                         text->vadj->value = MIN(text->vadj->value, upper);
1304                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1305                                                 "value_changed");
1306                 } else
1307                         return FALSE;
1308         } else {
1309                 if (text->vadj->value > 0.0) {
1310                         text->vadj->value -= page_incr;
1311                         text->vadj->value = MAX(text->vadj->value, 0.0);
1312                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1313                                                 "value_changed");
1314                 } else
1315                         return FALSE;
1316         }
1317
1318         return TRUE;
1319 }
1320
1321 static void textview_smooth_scroll_do(TextView *textview,
1322                                       gfloat old_value, gfloat last_value,
1323                                       gint step)
1324 {
1325         GtkSText *text = GTK_STEXT(textview->text);
1326         gint change_value;
1327         gboolean up;
1328         gint i;
1329
1330         if (old_value < last_value) {
1331                 change_value = last_value - old_value;
1332                 up = FALSE;
1333         } else {
1334                 change_value = old_value - last_value;
1335                 up = TRUE;
1336         }
1337
1338         gdk_key_repeat_disable();
1339
1340         for (i = step; i <= change_value; i += step) {
1341                 text->vadj->value = old_value + (up ? -i : i);
1342                 gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1343                                         "value_changed");
1344         }
1345
1346         text->vadj->value = last_value;
1347         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj), "value_changed");
1348
1349         gdk_key_repeat_restore();
1350 }
1351
1352 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1353 {
1354         GtkSText *text = GTK_STEXT(textview->text);
1355         gfloat upper;
1356         gfloat old_value;
1357         gfloat last_value;
1358
1359         if (!up) {
1360                 upper = text->vadj->upper - text->vadj->page_size;
1361                 if (text->vadj->value < upper) {
1362                         old_value = text->vadj->value;
1363                         last_value = text->vadj->value +
1364                                 text->vadj->step_increment * 4;
1365                         last_value = MIN(last_value, upper);
1366
1367                         textview_smooth_scroll_do(textview, old_value,
1368                                                   last_value,
1369                                                   prefs_common.scroll_step);
1370                 }
1371         } else {
1372                 if (text->vadj->value > 0.0) {
1373                         old_value = text->vadj->value;
1374                         last_value = text->vadj->value -
1375                                 text->vadj->step_increment * 4;
1376                         last_value = MAX(last_value, 0.0);
1377
1378                         textview_smooth_scroll_do(textview, old_value,
1379                                                   last_value,
1380                                                   prefs_common.scroll_step);
1381                 }
1382         }
1383 }
1384
1385 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1386 {
1387         GtkSText *text = GTK_STEXT(textview->text);
1388         gfloat upper;
1389         gfloat page_incr;
1390         gfloat old_value;
1391         gfloat last_value;
1392
1393         if (prefs_common.scroll_halfpage)
1394                 page_incr = text->vadj->page_increment / 2;
1395         else
1396                 page_incr = text->vadj->page_increment;
1397
1398         if (!up) {
1399                 upper = text->vadj->upper - text->vadj->page_size;
1400                 if (text->vadj->value < upper) {
1401                         old_value = text->vadj->value;
1402                         last_value = text->vadj->value + page_incr;
1403                         last_value = MIN(last_value, upper);
1404
1405                         textview_smooth_scroll_do(textview, old_value,
1406                                                   last_value,
1407                                                   prefs_common.scroll_step);
1408                 } else
1409                         return FALSE;
1410         } else {
1411                 if (text->vadj->value > 0.0) {
1412                         old_value = text->vadj->value;
1413                         last_value = text->vadj->value - page_incr;
1414                         last_value = MAX(last_value, 0.0);
1415
1416                         textview_smooth_scroll_do(textview, old_value,
1417                                                   last_value,
1418                                                   prefs_common.scroll_step);
1419                 } else
1420                         return FALSE;
1421         }
1422
1423         return TRUE;
1424 }
1425
1426 #define KEY_PRESS_EVENT_STOP() \
1427         if (gtk_signal_n_emissions_by_name \
1428                 (GTK_OBJECT(widget), "key_press_event") > 0) { \
1429                 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), \
1430                                              "key_press_event"); \
1431         }
1432
1433 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1434                                  TextView *textview)
1435 {
1436         SummaryView *summaryview = NULL;
1437         MessageView *messageview = textview->messageview;
1438
1439         if (!event) return FALSE;
1440         if (messageview->mainwin)
1441                 summaryview = messageview->mainwin->summaryview;
1442
1443         switch (event->keyval) {
1444         case GDK_Tab:
1445         case GDK_Home:
1446         case GDK_Left:
1447         case GDK_Up:
1448         case GDK_Right:
1449         case GDK_Down:
1450         case GDK_Page_Up:
1451         case GDK_Page_Down:
1452         case GDK_End:
1453         case GDK_Control_L:
1454         case GDK_Control_R:
1455                 break;
1456         case GDK_space:
1457                 if (summaryview)
1458                         summary_pass_key_press_event(summaryview, event);
1459                 else
1460                         textview_scroll_page(textview, FALSE);
1461                 break;
1462         case GDK_BackSpace:
1463                 textview_scroll_page(textview, TRUE);
1464                 break;
1465         case GDK_Return:
1466                 textview_scroll_one_line(textview,
1467                                          (event->state & GDK_MOD1_MASK) != 0);
1468                 break;
1469         case GDK_n:
1470         case GDK_N:
1471         case GDK_p:
1472         case GDK_P:
1473         case GDK_y:
1474         case GDK_t:
1475         case GDK_l:
1476                 if (messageview->type == MVIEW_MIME) {
1477                         KEY_PRESS_EVENT_STOP();
1478                         mimeview_pass_key_press_event(messageview->mimeview,
1479                                                       event);
1480                         break;
1481                 }
1482                 /* fall through */
1483         default:
1484                 if (summaryview)
1485                         summary_pass_key_press_event(summaryview, event);
1486                 break;
1487         }
1488
1489         return TRUE;
1490 }
1491
1492 static gint textview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1493                                     TextView *textview)
1494 {
1495         if (event)
1496                 textview->last_buttonpress = event->type;
1497         return FALSE;
1498 }
1499
1500 static gint textview_button_released(GtkWidget *widget, GdkEventButton *event,
1501                                     TextView *textview)
1502 {
1503         textview->cur_pos = 
1504                 gtk_editable_get_position(GTK_EDITABLE(textview->text));
1505
1506         if (event && 
1507             ((event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS)
1508              || event->button == 2 || event->button == 3)) {
1509                 GSList *cur;
1510
1511                 /* double click seems to set the cursor after the current
1512                  * word. The cursor position needs fixing, otherwise the
1513                  * last word of a clickable zone will not work */
1514                 if (event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS) {
1515                         textview->cur_pos--;
1516                 }
1517
1518                 for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1519                         RemoteURI *uri = (RemoteURI *)cur->data;
1520
1521                         if (textview->cur_pos >= uri->start &&
1522                             textview->cur_pos <  uri->end) {
1523                                 if (!g_strncasecmp(uri->uri, "mailto:", 7)) {
1524                                         if (event->button == 3) {
1525                                                 gchar *fromname, *fromaddress;
1526                                                 GdkEventButton tmpev;   
1527                                                 
1528                                                 /* extract url */
1529                                                 fromaddress = g_strdup(uri->uri + 7);
1530                                                 /* Hiroyuki: please put this function in utils.c! */
1531                                                 fromname = procheader_get_fromname(fromaddress);
1532                                                 extract_address(fromaddress);
1533                                                 g_message("adding from textview %s <%s>", fromname, fromaddress);
1534                                                 /* Add to address book - Match */
1535                                                 addressbook_add_contact( fromname, fromaddress, NULL );
1536                                                 
1537                                                 g_free(fromaddress);
1538                                                 g_free(fromname);
1539                                         } else {
1540                                                 PrefsAccount *account = NULL;
1541                                                 FolderItem   *folder_item;
1542
1543                                                 if (textview->messageview && textview->messageview->mainwin 
1544                                                 &&  textview->messageview->mainwin->summaryview 
1545                                                 &&  textview->messageview->mainwin->summaryview->folder_item) {
1546                                                         folder_item = textview->messageview->mainwin->summaryview->folder_item;
1547                                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
1548                                                                 account = account_find_from_id(folder_item->prefs->default_account);
1549                                                 }
1550                                                 compose_new_with_recipient
1551                                                         (account, uri->uri + 7);
1552                                         }
1553                                 } else {
1554                                         open_uri(uri->uri,
1555                                                  prefs_common.uri_cmd);
1556                                 }
1557                         }
1558                 }
1559         }
1560         if (event)
1561                 textview->last_buttonpress = event->type;
1562         return FALSE;
1563 }
1564
1565 static void textview_uri_list_remove_all(GSList *uri_list)
1566 {
1567         GSList *cur;
1568
1569         for (cur = uri_list; cur != NULL; cur = cur->next) {
1570                 if (cur->data) {
1571                         g_free(((RemoteURI *)cur->data)->uri);
1572                         g_free(cur->data);
1573                 }
1574         }
1575
1576         g_slist_free(uri_list);
1577 }