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