57a11c53acd5c557f51ed9fdba6f390ed583c6b3
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 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/gdkkeysyms.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkmenu.h>
30 #include <gtk/gtkmenuitem.h>
31 #include <gtk/gtkitemfactory.h>
32 #include <gtk/gtkcheckmenuitem.h>
33 #include <gtk/gtkoptionmenu.h>
34 #include <gtk/gtkwidget.h>
35 #include <gtk/gtkclist.h>
36 #include <gtk/gtkctree.h>
37 #include <gtk/gtkvpaned.h>
38 #include <gtk/gtkentry.h>
39 #include <gtk/gtkeditable.h>
40 #include <gtk/gtkwindow.h>
41 #include <gtk/gtksignal.h>
42 #include <gtk/gtkvbox.h>
43 #include <gtk/gtkcontainer.h>
44 #include <gtk/gtkhandlebox.h>
45 #include <gtk/gtktoolbar.h>
46 #include <gtk/gtktable.h>
47 #include <gtk/gtkhbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkscrolledwindow.h>
50 #include <gtk/gtkthemes.h>
51 #include <gtk/gtkdnd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <unistd.h>
57 #include <time.h>
58 /* #include <sys/utsname.h> */
59 #include <stdlib.h>
60 #include <sys/wait.h>
61 #include <signal.h>
62 #include <errno.h>
63
64 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
65 #  include <wchar.h>
66 #  include <wctype.h>
67 #endif
68
69
70 #include "gtkstext.h"
71
72 #include "intl.h"
73 #include "main.h"
74 #include "mainwindow.h"
75 #include "compose.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "send.h"
81 #include "news.h"
82 #include "customheader.h"
83 #include "prefs_common.h"
84 #include "prefs_account.h"
85 #include "account.h"
86 #include "filesel.h"
87 #include "procheader.h"
88 #include "procmime.h"
89 #include "statusbar.h"
90 #include "about.h"
91 #include "base64.h"
92 #include "codeconv.h"
93 #include "utils.h"
94 #include "gtkutils.h"
95 #include "socket.h"
96 #include "alertpanel.h"
97 #include "manage_window.h"
98 #include "gtkshruler.h"
99 #include "folder.h"
100 #include "addr_compl.h"
101 #include "quote_fmt.h"
102 #include "template.h"
103
104 #if USE_GPGME
105 #  include "rfc2015.h"
106 #endif
107
108 typedef enum
109 {
110         COL_MIMETYPE = 0,
111         COL_SIZE     = 1,
112         COL_NAME     = 2
113 } AttachColumnPos;
114
115 #define N_ATTACH_COLS           3
116
117 #define B64_LINE_SIZE           57
118 #define B64_BUFFSIZE            77
119
120 #define MAX_REFERENCES_LEN      999
121
122 static GdkColor quote_color = {0, 0, 0, 0xbfff};
123
124 static GList *compose_list = NULL;
125
126 static Compose *compose_create                  (PrefsAccount   *account,
127                                                  ComposeMode     mode);
128 static void compose_toolbar_create              (Compose        *compose,
129                                                  GtkWidget      *container);
130 static GtkWidget *compose_account_option_menu_create
131                                                 (Compose        *compose);
132 static void compose_set_template_menu           (Compose        *compose);
133 static void compose_destroy                     (Compose        *compose);
134
135 static gint compose_parse_header                (Compose        *compose,
136                                                  MsgInfo        *msginfo);
137 static gchar *compose_parse_references          (const gchar    *ref,
138                                                  const gchar    *msgid);
139
140 static gchar *compose_quote_fmt                 (Compose        *compose,
141                                                  MsgInfo        *msginfo,
142                                                  const gchar    *fmt,
143                                                  const gchar    *qmark);
144
145 static void compose_reply_set_entry             (Compose        *compose,
146                                                  MsgInfo        *msginfo,
147                                                  gboolean        to_all,
148                                                  gboolean        to_sender,
149                                                  gboolean
150                                                  followup_and_reply_to);
151 static void compose_reedit_set_entry            (Compose        *compose,
152                                                  MsgInfo        *msginfo);
153 static void compose_insert_sig                  (Compose        *compose);
154 static void compose_insert_file                 (Compose        *compose,
155                                                  const gchar    *file);
156 static void compose_attach_append               (Compose        *compose,
157                                                  const gchar    *file,
158                                                  ContentType     cnttype);
159 static void compose_attach_append_with_type(Compose *compose,
160                                             const gchar *file,
161                                             const gchar *type,
162                                             ContentType cnttype);
163 static void compose_wrap_line                   (Compose        *compose);
164 static void compose_wrap_line_all               (Compose        *compose);
165 static void compose_set_title                   (Compose        *compose);
166
167 static PrefsAccount *compose_current_mail_account(void);
168 /* static gint compose_send                     (Compose        *compose); */
169 static gint compose_write_to_file               (Compose        *compose,
170                                                  const gchar    *file,
171                                                  gboolean        is_draft);
172 static gint compose_write_body_to_file          (Compose        *compose,
173                                                  const gchar    *file);
174 static gint compose_save_to_outbox              (Compose        *compose,
175                                                  const gchar    *file);
176 static gint compose_remove_reedit_target        (Compose        *compose);
177 static gint compose_queue                       (Compose        *compose,
178                                                  const gchar    *file);
179 static void compose_write_attach                (Compose        *compose,
180                                                  FILE           *fp);
181 static gint compose_write_headers               (Compose        *compose,
182                                                  FILE           *fp,
183                                                  const gchar    *charset,
184                                                  EncodingType    encoding,
185                                                  gboolean        is_draft);
186
187 static void compose_convert_header              (gchar          *dest,
188                                                  gint            len,
189                                                  gchar          *src,
190                                                  gint            header_len);
191 static void compose_generate_msgid              (Compose        *compose,
192                                                  gchar          *buf,
193                                                  gint            len);
194
195 static void compose_attach_info_free            (AttachInfo     *ainfo);
196 static void compose_attach_remove_selected      (Compose        *compose);
197
198 static void compose_attach_property             (Compose        *compose);
199 static void compose_attach_property_create      (gboolean       *cancelled);
200 static void attach_property_ok                  (GtkWidget      *widget,
201                                                  gboolean       *cancelled);
202 static void attach_property_cancel              (GtkWidget      *widget,
203                                                  gboolean       *cancelled);
204 static gint attach_property_delete_event        (GtkWidget      *widget,
205                                                  GdkEventAny    *event,
206                                                  gboolean       *cancelled);
207 static void attach_property_key_pressed         (GtkWidget      *widget,
208                                                  GdkEventKey    *event,
209                                                  gboolean       *cancelled);
210
211 static void compose_exec_ext_editor             (Compose           *compose);
212 static gint compose_exec_ext_editor_real        (const gchar       *file);
213 static gboolean compose_ext_editor_kill         (Compose           *compose);
214 static void compose_input_cb                    (gpointer           data,
215                                                  gint               source,
216                                                  GdkInputCondition  condition);
217 static void compose_set_ext_editor_sensitive    (Compose           *compose,
218                                                  gboolean           sensitive);
219
220 static gint calc_cursor_xpos    (GtkSText       *text,
221                                  gint            extra,
222                                  gint            char_width);
223
224 static void compose_create_header_entry (Compose *compose);
225 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
226
227 /* callback functions */
228
229 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
230                                          GtkAllocation  *allocation,
231                                          GtkSHRuler     *shruler);
232
233 static void toolbar_send_cb             (GtkWidget      *widget,
234                                          gpointer        data);
235 static void toolbar_send_later_cb       (GtkWidget      *widget,
236                                          gpointer        data);
237 static void toolbar_draft_cb            (GtkWidget      *widget,
238                                          gpointer        data);
239 static void toolbar_insert_cb           (GtkWidget      *widget,
240                                          gpointer        data);
241 static void toolbar_attach_cb           (GtkWidget      *widget,
242                                          gpointer        data);
243 static void toolbar_sig_cb              (GtkWidget      *widget,
244                                          gpointer        data);
245 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
246                                          gpointer        data);
247 static void toolbar_linewrap_cb         (GtkWidget      *widget,
248                                          gpointer        data);
249 static void toolbar_address_cb          (GtkWidget      *widget,
250                                          gpointer        data);
251
252
253 static void select_account(Compose * compose, PrefsAccount * ac);
254 static void account_activated           (GtkMenuItem    *menuitem,
255                                          gpointer        data);
256
257 static void attach_selected             (GtkCList       *clist,
258                                          gint            row,
259                                          gint            column,
260                                          GdkEvent       *event,
261                                          gpointer        data);
262 static void attach_button_pressed       (GtkWidget      *widget,
263                                          GdkEventButton *event,
264                                          gpointer        data);
265 static void attach_key_pressed          (GtkWidget      *widget,
266                                          GdkEventKey    *event,
267                                          gpointer        data);
268
269 static void compose_send_cb             (gpointer        data,
270                                          guint           action,
271                                          GtkWidget      *widget);
272 static void compose_send_later_cb       (gpointer        data,
273                                          guint           action,
274                                          GtkWidget      *widget);
275
276 static void compose_draft_cb            (gpointer        data,
277                                          guint           action,
278                                          GtkWidget      *widget);
279
280 static void compose_attach_cb           (gpointer        data,
281                                          guint           action,
282                                          GtkWidget      *widget);
283 static void compose_insert_file_cb      (gpointer        data,
284                                          guint           action,
285                                          GtkWidget      *widget);
286
287 static void compose_close_cb            (gpointer        data,
288                                          guint           action,
289                                          GtkWidget      *widget);
290
291 static void compose_address_cb          (gpointer        data,
292                                          guint           action,
293                                          GtkWidget      *widget);
294 static void compose_template_activate_cb(GtkWidget      *widget,
295                                          gpointer        data);
296
297 static void compose_ext_editor_cb       (gpointer        data,
298                                          guint           action,
299                                          GtkWidget      *widget);
300
301 static gint compose_delete_cb           (GtkWidget      *widget,
302                                          GdkEventAny    *event,
303                                          gpointer        data);
304 static void compose_destroy_cb          (GtkWidget      *widget,
305                                          Compose        *compose);
306
307 static void compose_cut_cb              (Compose        *compose);
308 static void compose_copy_cb             (Compose        *compose);
309 static void compose_paste_cb            (Compose        *compose);
310 static void compose_allsel_cb           (Compose        *compose);
311
312 static void compose_grab_focus_cb       (GtkWidget      *widget,
313                                          Compose        *compose);
314
315 static void compose_changed_cb          (GtkEditable    *editable,
316                                          Compose        *compose);
317 static void compose_button_press_cb     (GtkWidget      *widget,
318                                          GdkEventButton *event,
319                                          Compose        *compose);
320 #if 0
321 static void compose_key_press_cb        (GtkWidget      *widget,
322                                          GdkEventKey    *event,
323                                          Compose        *compose);
324 #endif
325
326 static void compose_toggle_to_cb        (gpointer        data,
327                                          guint           action,
328                                          GtkWidget      *widget);
329 static void compose_toggle_cc_cb        (gpointer        data,
330                                          guint           action,
331                                          GtkWidget      *widget);
332 static void compose_toggle_bcc_cb       (gpointer        data,
333                                          guint           action,
334                                          GtkWidget      *widget);
335 static void compose_toggle_replyto_cb   (gpointer        data,
336                                          guint           action,
337                                          GtkWidget      *widget);
338 static void compose_toggle_followupto_cb(gpointer        data,
339                                          guint           action,
340                                          GtkWidget      *widget);
341 static void compose_toggle_attach_cb    (gpointer        data,
342                                          guint           action,
343                                          GtkWidget      *widget);
344 static void compose_toggle_ruler_cb     (gpointer        data,
345                                          guint           action,
346                                          GtkWidget      *widget);
347 #if USE_GPGME
348 static void compose_toggle_sign_cb      (gpointer        data,
349                                          guint           action,
350                                          GtkWidget      *widget);
351 static void compose_toggle_encrypt_cb   (gpointer        data,
352                                          guint           action,
353                                          GtkWidget      *widget);
354 #endif
355 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
356                                              GtkWidget *widget);
357
358 static void compose_attach_drag_received_cb (GtkWidget          *widget,
359                                              GdkDragContext     *drag_context,
360                                              gint                x,
361                                              gint                y,
362                                              GtkSelectionData   *data,
363                                              guint               info,
364                                              guint               time,
365                                              gpointer            user_data);
366 static void compose_insert_drag_received_cb (GtkWidget          *widget,
367                                              GdkDragContext     *drag_context,
368                                              gint                x,
369                                              gint                y,
370                                              GtkSelectionData   *data,
371                                              guint               info,
372                                              guint               time,
373                                              gpointer            user_data);
374
375 static void to_activated                (GtkWidget      *widget,
376                                          Compose        *compose);
377 static void newsgroups_activated        (GtkWidget      *widget,
378                                          Compose        *compose);
379 static void subject_activated           (GtkWidget      *widget,
380                                          Compose        *compose);
381 static void cc_activated                (GtkWidget      *widget,
382                                          Compose        *compose);
383 static void bcc_activated               (GtkWidget      *widget,
384                                          Compose        *compose);
385 static void replyto_activated           (GtkWidget      *widget,
386                                          Compose        *compose);
387 static void followupto_activated        (GtkWidget      *widget,
388                                          Compose        *compose);
389 static void compose_attach_parts(Compose * compose,
390                                  MsgInfo * msginfo);
391
392 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
393                                   gboolean to_all,
394                                   gboolean ignore_replyto,
395                                   gboolean followup_and_reply_to);
396
397 void compose_headerentry_changed_cb     (GtkWidget *entry,
398                                          compose_headerentry *headerentry);
399 void compose_headerentry_key_press_event_cb     (GtkWidget *entry,
400                                                  GdkEventKey *event,
401                                                  compose_headerentry *headerentry);
402
403 Compose * compose_generic_new (PrefsAccount     *account,
404                                const gchar      *to,
405                                FolderItem       *item);
406
407 static GtkItemFactoryEntry compose_popup_entries[] =
408 {
409         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
410         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
411         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
412         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
413 };
414
415 static GtkItemFactoryEntry compose_entries[] =
416 {
417         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
418         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb,      0, NULL},
419         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
420         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig,     0, NULL},
421         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
422         {N_("/_File/_Close"),                   "<alt>W", compose_close_cb, 0, NULL},
423
424         {N_("/_Edit"),             NULL, NULL, 0, "<Branch>"},
425         {N_("/_Edit/_Undo"),       "<control>Z", NULL, 0, NULL},
426         {N_("/_Edit/_Redo"),       "<control>Y", NULL, 0, NULL},
427         {N_("/_Edit/---"),         NULL, NULL, 0, "<Separator>"},
428         {N_("/_Edit/Cu_t"),        "<control>X", compose_cut_cb,    0, NULL},
429         {N_("/_Edit/_Copy"),       "<control>C", compose_copy_cb,   0, NULL},
430         {N_("/_Edit/_Paste"),      "<control>V", compose_paste_cb,  0, NULL},
431         {N_("/_Edit/Select _all"), "<control>A", compose_allsel_cb, 0, NULL},
432         {N_("/_Edit/---"),         NULL, NULL, 0, "<Separator>"},
433         {N_("/_Edit/_Wrap current paragraph"), "<alt>L", compose_wrap_line, 0, NULL},
434         {N_("/_Edit/Wrap all long _lines"),
435                         "<shift><alt>L", compose_wrap_line_all, 0, NULL},
436         {N_("/_Edit/Edit with e_xternal editor"),
437                         "<alt>X", compose_ext_editor_cb, 0, NULL},
438
439         {N_("/_Message"),               NULL, NULL, 0, "<Branch>"},
440         {N_("/_Message/_Send"),         "<control>Return",
441                                         compose_send_cb, 0, NULL},
442         {N_("/_Message/Send _later"),   "<shift><alt>S",
443                                         compose_send_later_cb,  0, NULL},
444         {N_("/_Message/Save to _draft folder"),
445                                         "<alt>D", compose_draft_cb, 0, NULL},
446 #if 0 /* NEW COMPOSE GUI */
447         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
448         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
449         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
450         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
451         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
452         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
453         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
454         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
455         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
456 #endif
457 #if USE_GPGME
458         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
459         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
460         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
461 #endif /* USE_GPGME */
462         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
463         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
464         {N_("/_Tool"),                  NULL, NULL, 0, "<Branch>"},
465         {N_("/_Tool/Show _ruler"),      NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
466         {N_("/_Tool/_Address book"),    "<alt>A", compose_address_cb , 0, NULL},
467         {N_("/_Tool/_Template"),        NULL, NULL, 0, "<Branch>"},
468         {N_("/_Help"),                  NULL, NULL, 0, "<LastBranch>"},
469         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
470 };
471
472 static GtkTargetEntry compose_mime_types[] =
473 {
474         {"text/uri-list", 0, 0}
475 };
476
477 Compose * compose_new(PrefsAccount *account)
478 {
479         return compose_generic_new(account, NULL, NULL);
480 }
481
482 Compose * compose_new_with_recipient(PrefsAccount *account, const gchar *to)
483 {
484         return compose_generic_new(account, to, NULL);
485 }
486
487 Compose * compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
488 {
489         return compose_generic_new(account, NULL, item);
490 }
491
492 static void set_compose_entries(Compose * compose, const gchar * mailto)
493 {
494         gchar * subject = NULL;
495         gchar * to = NULL;
496         gchar * cc = NULL;
497         gchar * bcc = NULL;
498         gchar * body = NULL;
499         gchar * p;
500         gchar * tmp_mailto;
501         gchar * cur;
502         
503         Xstrdup_a(tmp_mailto, mailto, return);
504
505         cur = tmp_mailto;
506
507         p = strchr(cur, '?');
508         if (p != NULL) {
509                 * p = 0;
510                 cur = p + 1;
511         }
512         to = tmp_mailto;
513
514         while (p) {
515                 char *field, *value;
516                 
517                 field = cur;
518
519                 p = strchr(cur, '=');
520                 if (p == NULL)
521                         break;
522                 * p = 0;
523                 cur = p + 1;
524
525                 value = cur;
526
527                 p = strchr(cur, '&');
528                 if (p != NULL) {
529                         * p = 0;
530                         cur = p + 1;
531                 }
532
533                 if (value) {
534                         if (g_strcasecmp(field, "subject")==0) {
535                                 Xstrdup_a(subject, value, );
536                                 if (subject != NULL)
537                                         decode_uri(subject, value);
538                         }
539                         else if (g_strcasecmp(field, "cc")==0)
540                                 cc = value;
541                         else if (g_strcasecmp(field, "bcc")==0)
542                                 bcc = value;
543                         else if (g_strcasecmp(field, "body")==0) {
544                                 Xstrdup_a(body, value, );
545                                 if (body != NULL)
546                                         decode_uri(body, value);
547                         }
548                 }
549         }                       
550
551         if (to) {
552                 compose_entry_append(compose, to, COMPOSE_TO);
553                 /*
554                 gtk_widget_grab_focus(compose->text);
555                 */
556         }
557
558         if (subject)
559                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
560         if (cc)
561                 compose_entry_append(compose, cc, COMPOSE_CC);
562         if (bcc)
563                 compose_entry_append(compose, bcc, COMPOSE_BCC);
564         if (body) {
565                 gtk_stext_insert(GTK_STEXT(compose->text),
566                                  NULL, NULL, NULL, body, -1);
567                 gtk_stext_insert(GTK_STEXT(compose->text),
568                                  NULL, NULL, NULL, "\n", 1);
569         }
570 }       
571
572 Compose * compose_generic_new(PrefsAccount *account, const gchar *to, FolderItem *item)
573 {
574         Compose *compose;
575
576         if (item && item->prefs && item->prefs->enable_default_account)
577                 account = account_find_from_id(item->prefs->default_account);
578
579         if (!account) account = cur_account;
580         g_return_val_if_fail(account != NULL, NULL);
581
582         compose = compose_create(account, COMPOSE_NEW);
583         compose->replyinfo = NULL;
584
585         if (prefs_common.auto_sig)
586                 compose_insert_sig(compose);
587         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
588         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
589
590         if (account->protocol != A_NNTP) {
591                 if (to) {
592                         set_compose_entries(compose, to);
593
594                 } else if(item && item->prefs->enable_default_to) {
595                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
596                 }
597                 if (item && item->ret_rcpt) {
598                         GtkItemFactory *ifactory;
599                 
600                         ifactory = gtk_item_factory_from_widget(compose->menubar);
601                         menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
602                 }
603         } else {
604                 if (to) {
605                         compose_entry_append(compose, to, COMPOSE_NEWSGROUPS);
606                 }
607         }
608         gtk_widget_grab_focus(compose->subject_entry);
609
610         if (prefs_common.auto_exteditor)
611                 compose_exec_ext_editor(compose);
612
613         return compose;
614 }
615
616 #define CHANGE_FLAGS(msginfo) \
617 { \
618 if (msginfo->folder->folder->change_flags != NULL) \
619 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
620                                       msginfo->folder, \
621                                       msginfo); \
622 }
623
624 /*
625 Compose * compose_new_followup_and_replyto(PrefsAccount *account,
626                                            const gchar *followupto, gchar * to)
627 {
628         Compose *compose;
629
630         if (!account) account = cur_account;
631         g_return_val_if_fail(account != NULL, NULL);
632         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
633
634         compose = compose_create(account, COMPOSE_NEW);
635
636         if (prefs_common.auto_sig)
637                 compose_insert_sig(compose);
638         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
639         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
640
641         compose_entry_append(compose, to, COMPOSE_TO);
642         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
643         gtk_widget_grab_focus(compose->subject_entry);
644
645         return compose;
646 }
647 */
648
649 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
650                    gboolean ignore_replyto)
651 {
652         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, FALSE);
653 }
654
655 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
656                                    gboolean to_all,
657                                    gboolean ignore_replyto)
658 {
659         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, TRUE);
660 }
661
662 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
663                                   gboolean to_all,
664                                   gboolean ignore_replyto,
665                                   gboolean followup_and_reply_to)
666 {
667         Compose *compose;
668         PrefsAccount *account;
669         PrefsAccount *reply_account;
670         GtkSText *text;
671
672         g_return_if_fail(msginfo != NULL);
673         g_return_if_fail(msginfo->folder != NULL);
674
675         account = NULL;
676         /* select the account set in folderitem's property (if enabled) */
677         if (msginfo->folder->prefs && msginfo->folder->prefs->enable_default_account)
678                 account = account_find_from_id(msginfo->folder->prefs->default_account);
679         
680         /* select the account for the whole folder (IMAP / NNTP) */
681         if (!account)
682                 account = msginfo->folder->folder->account;
683
684         /* select account by to: and cc: header if enabled */
685         if (prefs_common.reply_account_autosel) {
686                 if (!account && msginfo->to) {
687                         gchar *to;
688                         Xstrdup_a(to, msginfo->to, return);
689                         extract_address(to);
690                         account = account_find_from_address(to);
691                 }
692                 if (!account) {
693                         gchar cc[BUFFSIZE];
694                         if(!get_header_from_msginfo(msginfo, cc, sizeof(cc), "CC:")) { /* Found a CC header */
695                                 extract_address(cc);
696                                 account = account_find_from_address(cc);
697                         }        
698                 }
699         }
700
701         /* select current account */
702         if (!account) account = cur_account;
703         g_return_if_fail(account != NULL);
704
705         if (ignore_replyto && account->protocol == A_NNTP &&
706             !followup_and_reply_to) {
707                 reply_account =
708                         account_find_from_address(account->address);
709                 if (!reply_account)
710                         reply_account = compose_current_mail_account();
711                 if (!reply_account)
712                         return;
713         } else
714                 reply_account = account;
715
716         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
717         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
718
719         CHANGE_FLAGS(msginfo);
720
721         compose = compose_create(account, COMPOSE_REPLY);
722         compose->replyinfo = procmsg_msginfo_copy(msginfo);
723
724 #if 0 /* NEW COMPOSE GUI */
725         if (followup_and_reply_to) {
726                 gtk_widget_show(compose->to_hbox);
727                 gtk_widget_show(compose->to_entry);
728                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
729                 compose->use_to = TRUE;
730         }
731 #endif
732         if (msginfo->folder && msginfo->folder->ret_rcpt) {
733                 GtkItemFactory *ifactory;
734         
735                 ifactory = gtk_item_factory_from_widget(compose->menubar);
736                 menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
737         }
738
739         if (compose_parse_header(compose, msginfo) < 0) return;
740         compose_reply_set_entry(compose, msginfo, to_all, ignore_replyto,
741                                 followup_and_reply_to);
742
743         text = GTK_STEXT(compose->text);
744         gtk_stext_freeze(text);
745
746         if (quote) {
747                 gchar *qmark;
748                 gchar *quote_str;
749
750                 if (prefs_common.quotemark && *prefs_common.quotemark)
751                         qmark = prefs_common.quotemark;
752                 else
753                         qmark = "> ";
754
755                 quote_str = compose_quote_fmt(compose, msginfo,
756                                               prefs_common.quotefmt,
757                                               qmark);
758         }
759
760         if (prefs_common.auto_sig)
761                 compose_insert_sig(compose);
762         gtk_editable_set_position(GTK_EDITABLE(text), 0);
763         gtk_stext_set_point(text, 0);
764
765         if (quote && prefs_common.linewrap_quote) {
766                 compose_wrap_line_all(compose);
767         }
768
769         gtk_stext_thaw(text);
770         gtk_widget_grab_focus(compose->text);
771
772         if (prefs_common.auto_exteditor)
773                 compose_exec_ext_editor(compose);
774 }
775
776
777 static gchar *procmime_get_file_name(MimeInfo *mimeinfo)
778 {
779         gchar *base;
780         gchar *filename;
781
782         g_return_val_if_fail(mimeinfo != NULL, NULL);
783
784         base = mimeinfo->filename ? mimeinfo->filename
785                 : mimeinfo->name ? mimeinfo->name : NULL;
786
787         if (MIME_TEXT_HTML == mimeinfo->mime_type && base == NULL){
788                 filename = g_strdup_printf("%s%smimetmp%i.html",
789                                            get_mime_tmp_dir(),
790                                            G_DIR_SEPARATOR_S,
791                                            mimeinfo);
792                 return filename;
793         }
794         else {
795                 base = base ? base : "";
796                 base = g_basename(base);
797                 if (*base == '\0') {
798                         filename = g_strdup_printf("%s%smimetmp%i",
799                                                    get_mime_tmp_dir(),
800                                                    G_DIR_SEPARATOR_S,
801                                                    mimeinfo);
802                         return filename;
803                 }
804         }
805
806         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
807                                base, NULL);
808
809         return filename;
810 }
811
812 static gchar * mime_extract_file(gchar * source, MimeInfo *partinfo)
813 {
814         gchar *filename;
815
816         if (!partinfo) return;
817
818         filename = procmime_get_file_name(partinfo);
819
820         if (procmime_get_part(filename, source, partinfo) < 0)
821                 alertpanel_error
822                         (_("Can't get the part of multipart message."));
823
824         return filename;
825 }
826
827 static void compose_attach_parts(Compose * compose,
828                                  MsgInfo * msginfo)
829 {
830
831         FILE *fp;
832         gchar *file;
833         MimeInfo *mimeinfo;
834         MsgInfo *tmpmsginfo;
835         gchar *p;
836         gchar *boundary;
837         gint boundary_len = 0;
838         gchar buf[BUFFSIZE];
839         glong fpos, prev_fpos;
840         gint npart;
841         gchar * source;
842         gchar * filename;
843
844         g_return_if_fail(msginfo != NULL);
845         
846 #if USE_GPGME
847         for (;;) {
848                 if ((fp = procmsg_open_message(msginfo)) == NULL) return;
849                 mimeinfo = procmime_scan_mime_header(fp);
850                 if (!mimeinfo) break;
851
852                 if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
853                     rfc2015_is_encrypted(mimeinfo)) {
854                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
855                 }
856                 if (MSG_IS_ENCRYPTED(msginfo->flags) &&
857                     !msginfo->plaintext_file  &&
858                     !msginfo->decryption_failed) {
859                         rfc2015_decrypt_message(msginfo, mimeinfo, fp);
860                         if (msginfo->plaintext_file &&
861                             !msginfo->decryption_failed) {
862                                 fclose(fp);
863                                 continue;
864                         }
865                 }
866                 
867                 break;
868         }
869 #else /* !USE_GPGME */
870         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
871         mimeinfo = procmime_scan_mime_header(fp);
872 #endif /* USE_GPGME */
873
874         fclose(fp);
875         if (!mimeinfo) return;
876         if (mimeinfo->mime_type == MIME_TEXT)
877                 return;
878
879         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
880
881         g_return_if_fail(mimeinfo != NULL);
882         g_return_if_fail(mimeinfo->mime_type != MIME_TEXT);
883
884         if (mimeinfo->mime_type == MIME_MULTIPART) {
885                 g_return_if_fail(mimeinfo->boundary != NULL);
886                 g_return_if_fail(mimeinfo->sub == NULL);
887         }
888         g_return_if_fail(fp != NULL);
889
890         boundary = mimeinfo->boundary;
891
892         if (boundary) {
893                 boundary_len = strlen(boundary);
894
895                 /* look for first boundary */
896                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL)
897                         if (IS_BOUNDARY(buf, boundary, boundary_len)) break;
898                 if (!p) {
899                         fclose(fp);
900                         return;
901                 }
902         }
903
904         if ((fpos = ftell(fp)) < 0) {
905                 perror("ftell");
906                 fclose(fp);
907                 return;
908         }
909
910         for (npart = 0;; npart++) {
911                 MimeInfo *partinfo;
912                 gboolean eom = FALSE;
913
914                 prev_fpos = fpos;
915
916                 partinfo = procmime_scan_mime_header(fp);
917                 if (!partinfo) break;
918
919                 if (npart != 0)
920                         procmime_mimeinfo_insert(mimeinfo, partinfo);
921                 else
922                         procmime_mimeinfo_free(partinfo);
923
924                 /* look for next boundary */
925                 buf[0] = '\0';
926                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
927                         if (IS_BOUNDARY(buf, boundary, boundary_len)) {
928                                 if (buf[2 + boundary_len]     == '-' &&
929                                     buf[2 + boundary_len + 1] == '-')
930                                         eom = TRUE;
931                                 break;
932                         }
933                 }
934                 if (p == NULL)
935                         eom = TRUE;     /* broken MIME message */
936                 fpos = ftell(fp);
937
938                 partinfo->size = fpos - prev_fpos - strlen(buf);
939
940                 if (eom) break;
941         }
942
943         source = procmsg_get_message_file_path(msginfo);
944
945         g_return_if_fail(mimeinfo != NULL);
946
947         if (!mimeinfo->main && mimeinfo->parent)
948                 {
949                         filename = mime_extract_file(source, mimeinfo);
950
951                         compose_attach_append_with_type(compose, filename,
952                                                         mimeinfo->content_type,
953                                                         mimeinfo->mime_type);
954
955                         g_free(filename);
956                 }
957
958         if (mimeinfo->sub && mimeinfo->sub->children)
959                 {
960                         filename = mime_extract_file(source, mimeinfo->sub);
961
962                         compose_attach_append_with_type(compose, filename,
963                                                         mimeinfo->content_type,
964                                                         mimeinfo->sub->mime_type);
965
966                         g_free(filename);
967                 }
968
969         if (mimeinfo->children) {
970                 MimeInfo *child;
971
972                 child = mimeinfo->children;
973                 while (child) {
974                         filename = mime_extract_file(source, child);
975
976                         compose_attach_append_with_type(compose, filename,
977                                                         child->content_type,
978                                                         child->mime_type);
979
980                         g_free(filename);
981
982                         child = child->next;
983                 }
984         }
985
986         fclose(fp);
987
988         procmime_mimeinfo_free_all(mimeinfo);
989 }
990
991
992 #define INSERT_FW_HEADER(var, hdr) \
993 if (msginfo->var && *msginfo->var) { \
994         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
995         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
996         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
997 }
998
999 Compose *compose_forward(PrefsAccount * account, MsgInfo *msginfo,
1000                          gboolean as_attach)
1001 {
1002         Compose *compose;
1003         /*      PrefsAccount *account; */
1004         GtkSText *text;
1005
1006         g_return_val_if_fail(msginfo != NULL, NULL);
1007         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1008
1009         account = msginfo->folder->folder->account;
1010         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
1011                 gchar *to;
1012                 Xstrdup_a(to, msginfo->to, return);
1013                 extract_address(to);
1014                 account = account_find_from_address(to);
1015         }
1016
1017         if(!account && prefs_common.forward_account_autosel) {
1018                 gchar cc[BUFFSIZE];
1019                 if(!get_header_from_msginfo(msginfo,cc,sizeof(cc),"CC:")){ /* Found a CC header */
1020                         extract_address(cc);
1021                         account = account_find_from_address(cc);
1022                 }
1023         }
1024
1025         if (account == NULL) {
1026                 account = cur_account;
1027                 /*
1028                 account = msginfo->folder->folder->account;
1029                 if (!account) account = cur_account;
1030                 */
1031         }
1032         g_return_val_if_fail(account != NULL, NULL);
1033
1034         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
1035         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
1036         CHANGE_FLAGS(msginfo);
1037
1038         compose = compose_create(account, COMPOSE_FORWARD);
1039
1040         if (msginfo->subject && *msginfo->subject) {
1041                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
1042                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
1043                                       msginfo->subject);
1044         }
1045
1046         text = GTK_STEXT(compose->text);
1047         gtk_stext_freeze(text);
1048
1049         if (as_attach) {
1050                 gchar *msgfile;
1051
1052                 msgfile = procmsg_get_message_file_path(msginfo);
1053                 if (!is_file_exist(msgfile))
1054                         g_warning(_("%s: file not exist\n"), msgfile);
1055                 else
1056                         compose_attach_append(compose, msgfile,
1057                                               MIME_MESSAGE_RFC822);
1058
1059                 g_free(msgfile);
1060         } else {
1061                 gchar *qmark;
1062                 gchar *quote_str;
1063
1064                 if (prefs_common.fw_quotemark && *prefs_common.fw_quotemark)
1065                         qmark = prefs_common.fw_quotemark;
1066                 else
1067                         qmark = "> ";
1068
1069                 quote_str = compose_quote_fmt(compose, msginfo,
1070                                               prefs_common.fw_quotefmt, qmark);
1071                 compose_attach_parts(compose, msginfo);
1072         }
1073
1074         if (prefs_common.auto_sig)
1075                 compose_insert_sig(compose);
1076         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1077         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1078
1079         gtk_stext_thaw(text);
1080 #if 0 /* NEW COMPOSE GUI */
1081         if (account->protocol != A_NNTP)
1082                 gtk_widget_grab_focus(compose->to_entry);
1083         else
1084                 gtk_widget_grab_focus(compose->newsgroups_entry);
1085 #endif
1086         gtk_widget_grab_focus(compose->header_last->entry);
1087
1088         if (prefs_common.auto_exteditor)
1089                 compose_exec_ext_editor(compose);
1090
1091         return compose;
1092 }
1093
1094 #undef INSERT_FW_HEADER
1095
1096 Compose * compose_forward_multiple(PrefsAccount * account, 
1097                           GSList *msginfo_list) 
1098 {
1099         Compose *compose;
1100         GtkSText *text;
1101         GSList *msginfo;
1102         gchar *msgfile;
1103
1104         g_return_val_if_fail(msginfo_list != NULL, NULL);
1105         
1106         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1107                 if ( ((MsgInfo *)msginfo->data)->folder == NULL )
1108                         return NULL;
1109         }
1110
1111         if (account == NULL) {
1112                 account = cur_account;
1113                 /*
1114                 account = msginfo->folder->folder->account;
1115                 if (!account) account = cur_account;
1116                 */
1117         }
1118         g_return_val_if_fail(account != NULL, NULL);
1119
1120         compose = compose_create(account, COMPOSE_FORWARD);
1121
1122         text = GTK_STEXT(compose->text);
1123         gtk_stext_freeze(text);
1124
1125         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1126                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1127                 if (!is_file_exist(msgfile))
1128                         g_warning(_("%s: file not exist\n"), msgfile);
1129                 else
1130                         compose_attach_append(compose, msgfile,
1131                                 MIME_MESSAGE_RFC822);
1132                 g_free(msgfile);
1133         }
1134
1135         if (prefs_common.auto_sig)
1136                 compose_insert_sig(compose);
1137         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1138         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1139
1140         gtk_stext_thaw(text);
1141 #if 0 /* NEW COMPOSE GUI */
1142         if (account->protocol != A_NNTP)
1143                 gtk_widget_grab_focus(compose->to_entry);
1144         else
1145                 gtk_widget_grab_focus(compose->newsgroups_entry);
1146 #endif
1147
1148         return compose;
1149 }
1150
1151 void compose_reedit(MsgInfo *msginfo)
1152 {
1153         Compose *compose;
1154         PrefsAccount *account;
1155         GtkSText *text;
1156         FILE *fp;
1157         gchar buf[BUFFSIZE];
1158
1159         g_return_if_fail(msginfo != NULL);
1160         g_return_if_fail(msginfo->folder != NULL);
1161
1162         account = msginfo->folder->folder->account;
1163
1164         if(!account&& prefs_common.reedit_account_autosel) {
1165                 gchar from[BUFFSIZE];
1166                 if(!get_header_from_msginfo(msginfo,from,sizeof(from),"FROM:")){ /* Found a FROM header */
1167                         extract_address(from);
1168                         account = account_find_from_address(from);
1169                 }
1170         }
1171         if (!account) account = cur_account;
1172         g_return_if_fail(account != NULL);
1173
1174         compose = compose_create(account, COMPOSE_REEDIT);
1175         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1176
1177         if (compose_parse_header(compose, msginfo) < 0) return;
1178         compose_reedit_set_entry(compose, msginfo);
1179
1180         text = GTK_STEXT(compose->text);
1181         gtk_stext_freeze(text);
1182
1183         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1184                 g_warning(_("Can't get text part\n"));
1185         else {
1186                 while (fgets(buf, sizeof(buf), fp) != NULL)
1187                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1188                 fclose(fp);
1189         }
1190         compose_attach_parts(compose, msginfo);
1191
1192         gtk_stext_thaw(text);
1193         gtk_widget_grab_focus(compose->text);
1194
1195         if (prefs_common.auto_exteditor)
1196                 compose_exec_ext_editor(compose);
1197 }
1198
1199 GList *compose_get_compose_list(void)
1200 {
1201         return compose_list;
1202 }
1203
1204 void compose_entry_append(Compose *compose, const gchar *address,
1205                           ComposeEntryType type)
1206 {
1207         GtkEntry *entry;
1208         const gchar *text;
1209         gchar *header;
1210
1211         if (!address || *address == '\0') return;
1212
1213 #if 0 /* NEW COMPOSE GUI */
1214         switch (type) {
1215         case COMPOSE_CC:
1216                 entry = GTK_ENTRY(compose->cc_entry);
1217                 break;
1218         case COMPOSE_BCC:
1219                 entry = GTK_ENTRY(compose->bcc_entry);
1220                 break;
1221         case COMPOSE_NEWSGROUPS:
1222                 entry = GTK_ENTRY(compose->newsgroups_entry);
1223                 break;
1224         case COMPOSE_TO:
1225         default:
1226                 entry = GTK_ENTRY(compose->to_entry);
1227                 break;
1228         }
1229
1230         text = gtk_entry_get_text(entry);
1231         if (*text != '\0')
1232                 gtk_entry_append_text(entry, ", ");
1233         gtk_entry_append_text(entry, address);
1234 #endif
1235
1236         switch (type) {
1237         case COMPOSE_CC:
1238                 header = N_("Cc:");
1239                 break;
1240         case COMPOSE_BCC:
1241                 header = N_("Bcc:");
1242                 break;
1243         case COMPOSE_REPLYTO:
1244                 header = N_("Reply-To:");
1245                 break;
1246         case COMPOSE_NEWSGROUPS:
1247                 header = N_("Newsgroups:");
1248                 break;
1249         case COMPOSE_FOLLOWUPTO:
1250                 header = N_( "Followup-To:");
1251                 break;
1252         case COMPOSE_TO:
1253         default:
1254                 header = N_("To:");
1255                 break;
1256         }
1257         header = prefs_common.trans_hdr ? gettext(header) : header;
1258
1259         compose_add_header_entry(compose, header, (gchar *)address);
1260 }
1261
1262 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1263 {
1264         static HeaderEntry hentry[] = {{"Reply-To:",       NULL, TRUE},
1265                                        {"Cc:",             NULL, FALSE},
1266                                        {"References:",     NULL, FALSE},
1267                                        {"Bcc:",            NULL, FALSE},
1268                                        {"Newsgroups:",     NULL, FALSE},
1269                                        {"Followup-To:",    NULL, FALSE},
1270                                        {"X-Mailing-List:", NULL, FALSE},
1271                                        {"X-BeenThere:",    NULL, FALSE},
1272                                        {NULL,              NULL, FALSE}};
1273
1274         enum
1275         {
1276                 H_REPLY_TO       = 0,
1277                 H_CC             = 1,
1278                 H_REFERENCES     = 2,
1279                 H_BCC            = 3,
1280                 H_NEWSGROUPS     = 4,
1281                 H_FOLLOWUP_TO    = 5,
1282                 H_X_MAILING_LIST = 6,
1283                 H_X_BEENTHERE    = 7
1284         };
1285
1286         FILE *fp;
1287
1288         g_return_val_if_fail(msginfo != NULL, -1);
1289
1290         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1291         procheader_get_header_fields(fp, hentry);
1292         fclose(fp);
1293
1294         if (hentry[H_REPLY_TO].body != NULL) {
1295                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1296                 compose->replyto = hentry[H_REPLY_TO].body;
1297                 hentry[H_REPLY_TO].body = NULL;
1298         }
1299         if (hentry[H_CC].body != NULL) {
1300                 conv_unmime_header_overwrite(hentry[H_CC].body);
1301                 compose->cc = hentry[H_CC].body;
1302                 hentry[H_CC].body = NULL;
1303         }
1304         if (hentry[H_X_MAILING_LIST].body != NULL) {
1305                 /* this is good enough to parse debian-devel */
1306                 char * buf = g_malloc(strlen(hentry[H_X_MAILING_LIST].body) + 1);
1307                 g_return_val_if_fail(buf != NULL, -1 );
1308                 if (1 == sscanf(hentry[H_X_MAILING_LIST].body, "<%[^>]>", buf))
1309                         compose->mailinglist = g_strdup(buf);
1310                 g_free(buf);
1311                 g_free(hentry[H_X_MAILING_LIST].body);
1312                 hentry[H_X_MAILING_LIST].body = NULL ;
1313         }
1314         if (hentry[H_X_BEENTHERE].body != NULL) {
1315                 /* this is good enough to parse the sylpheed-claws lists */
1316                 char * buf = g_malloc(strlen(hentry[H_X_BEENTHERE].body) + 1);
1317                 g_return_val_if_fail(buf != NULL, -1 );
1318                 if (1 == sscanf(hentry[H_X_BEENTHERE].body, "%[^>]", buf))
1319                         compose->mailinglist = g_strdup(buf);
1320                 g_free(buf);
1321                 g_free(hentry[H_X_BEENTHERE].body);
1322                 hentry[H_X_BEENTHERE].body = NULL ;
1323         }
1324         if (hentry[H_REFERENCES].body != NULL) {
1325                 if (compose->mode == COMPOSE_REEDIT)
1326                         compose->references = hentry[H_REFERENCES].body;
1327                 else {
1328                         compose->references = compose_parse_references
1329                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1330                         g_free(hentry[H_REFERENCES].body);
1331                 }
1332                 hentry[H_REFERENCES].body = NULL;
1333         }
1334         if (hentry[H_BCC].body != NULL) {
1335                 if (compose->mode == COMPOSE_REEDIT) {
1336                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1337                         compose->bcc = hentry[H_BCC].body;
1338                 } else
1339                         g_free(hentry[H_BCC].body);
1340                 hentry[H_BCC].body = NULL;
1341         }
1342         if (hentry[H_NEWSGROUPS].body != NULL) {
1343                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1344                 hentry[H_NEWSGROUPS].body = NULL;
1345         }
1346         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1347                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1348                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1349                 hentry[H_FOLLOWUP_TO].body = NULL;
1350         }
1351
1352         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1353                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1354         else if (compose->mode != COMPOSE_REEDIT &&
1355                  msginfo->msgid && *msginfo->msgid) {
1356                 compose->inreplyto = g_strdup(msginfo->msgid);
1357
1358                 if (!compose->references) {
1359                         if (msginfo->inreplyto && *msginfo->inreplyto)
1360                                 compose->references =
1361                                         g_strdup_printf("<%s>\n\t<%s>",
1362                                                         msginfo->inreplyto,
1363                                                         msginfo->msgid);
1364                         else
1365                                 compose->references =
1366                                         g_strconcat("<", msginfo->msgid, ">",
1367                                                     NULL);
1368                 }
1369         }
1370
1371         return 0;
1372 }
1373
1374 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1375 {
1376         GSList *ref_id_list, *cur;
1377         GString *new_ref;
1378         gchar *new_ref_str;
1379
1380         ref_id_list = references_list_append(NULL, ref);
1381         if (!ref_id_list) return NULL;
1382         if (msgid && *msgid)
1383                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1384
1385         for (;;) {
1386                 gint len = 0;
1387
1388                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1389                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1390                         len += strlen((gchar *)cur->data) + 5;
1391
1392                 if (len > MAX_REFERENCES_LEN) {
1393                         /* remove second message-ID */
1394                         if (ref_id_list && ref_id_list->next &&
1395                             ref_id_list->next->next) {
1396                                 g_free(ref_id_list->next->data);
1397                                 ref_id_list = g_slist_remove
1398                                         (ref_id_list, ref_id_list->next->data);
1399                         } else {
1400                                 slist_free_strings(ref_id_list);
1401                                 g_slist_free(ref_id_list);
1402                                 return NULL;
1403                         }
1404                 } else
1405                         break;
1406         }
1407
1408         new_ref = g_string_new("");
1409         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1410                 if (new_ref->len > 0)
1411                         g_string_append(new_ref, "\n\t");
1412                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1413         }
1414
1415         slist_free_strings(ref_id_list);
1416         g_slist_free(ref_id_list);
1417
1418         new_ref_str = new_ref->str;
1419         g_string_free(new_ref, FALSE);
1420
1421         return new_ref_str;
1422 }
1423
1424 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1425                                 const gchar *fmt, const gchar *qmark)
1426 {
1427         GtkSText *text = GTK_STEXT(compose->text);
1428         gchar *quote_str = NULL;
1429         gchar *buf;
1430         gchar *p, *lastp;
1431         gint len;
1432
1433         if (qmark != NULL) {
1434                 quote_fmt_init(msginfo, NULL);
1435                 quote_fmt_scan_string(qmark);
1436                 quote_fmt_parse();
1437
1438                 buf = quote_fmt_get_buffer();
1439                 if (buf == NULL)
1440                         alertpanel_error(_("Quote mark format error."));
1441                 else
1442                         Xstrdup_a(quote_str, buf, return NULL)
1443         }
1444
1445         quote_fmt_init(msginfo, quote_str);
1446         quote_fmt_scan_string(fmt);
1447         quote_fmt_parse();
1448
1449         buf = quote_fmt_get_buffer();
1450         if (buf == NULL) {
1451                 alertpanel_error(_("Message reply/forward format error."));
1452                 return NULL;
1453         }
1454
1455         gtk_stext_freeze(text);
1456         gtk_stext_set_point(text, 0);
1457         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
1458
1459         for (p = buf; *p != '\0'; ) {
1460                 lastp = strchr(p, '\n');
1461                 len = lastp ? lastp - p + 1 : -1;
1462                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1463                 if (lastp)
1464                         p = lastp + 1;
1465                 else
1466                         break;
1467         }
1468
1469         gtk_stext_thaw(text);
1470
1471         return buf;
1472 }
1473
1474 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1475                                     gboolean to_all, gboolean ignore_replyto,
1476                                     gboolean followup_and_reply_to)
1477 {
1478         GSList *cc_list;
1479         GSList *cur;
1480         gchar *from;
1481         GHashTable *to_table;
1482
1483         g_return_if_fail(compose->account != NULL);
1484         g_return_if_fail(msginfo != NULL);
1485
1486         if ((compose->account->protocol != A_NNTP) || followup_and_reply_to)
1487                 compose_entry_append(compose,
1488                                     ((compose->mailinglist && !ignore_replyto)
1489                                      ? compose->mailinglist
1490                                      : (compose->replyto && !ignore_replyto)
1491                                      ? compose->replyto
1492                                      : msginfo->from ? msginfo->from : ""),
1493                                      COMPOSE_TO);
1494         if (compose->account->protocol == A_NNTP)
1495                 if (ignore_replyto)
1496                         compose_entry_append(compose,
1497                                              msginfo->from ? msginfo->from : "",
1498                                              COMPOSE_TO);
1499                 else
1500                         compose_entry_append(compose,
1501                                              compose->followup_to ? compose->followup_to
1502                                              : compose->newsgroups ? compose->newsgroups
1503                                              : "",
1504                                              COMPOSE_NEWSGROUPS);
1505         /*
1506                 compose_entry_append(compose,
1507                                      compose->followup_to ? compose->followup_to
1508                                      : compose->newsgroups ? compose->newsgroups
1509                                      : "",
1510                                      COMPOSE_NEWSGROUPS);
1511         */
1512
1513         if (msginfo->subject && *msginfo->subject) {
1514                 gchar *buf, *buf2, *p;
1515
1516                 buf = g_strdup(msginfo->subject);
1517                 while (!strncasecmp(buf, "Re:", 3)) {
1518                         p = buf + 3;
1519                         while (isspace(*p)) p++;
1520                         memmove(buf, p, strlen(p) + 1);
1521                 }
1522
1523                 buf2 = g_strdup_printf("Re: %s", buf);
1524                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1525                 g_free(buf2);
1526                 g_free(buf);
1527         } else
1528                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1529
1530         if (!to_all || compose->account->protocol == A_NNTP) return;
1531
1532         from = g_strdup(compose->replyto ? compose->replyto :
1533                         msginfo->from ? msginfo->from : "");
1534         extract_address(from);
1535
1536         cc_list = address_list_append(NULL, msginfo->to);
1537         cc_list = address_list_append(cc_list, compose->cc);
1538
1539         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1540         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1541         if (compose->account)
1542                 g_hash_table_insert(to_table, compose->account->address,
1543                                     GINT_TO_POINTER(1));
1544
1545         /* remove address on To: and that of current account */
1546         for (cur = cc_list; cur != NULL; ) {
1547                 GSList *next = cur->next;
1548
1549                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1550                         cc_list = g_slist_remove(cc_list, cur->data);
1551                 else
1552                         g_hash_table_insert(to_table, cur->data, cur);
1553
1554                 cur = next;
1555         }
1556         g_hash_table_destroy(to_table);
1557         g_free(from);
1558
1559         if (cc_list) {
1560                 for (cur = cc_list; cur != NULL; cur = cur->next)
1561                         compose_entry_append(compose, (gchar *)cur->data,
1562                                              COMPOSE_CC);
1563                 slist_free_strings(cc_list);
1564                 g_slist_free(cc_list);
1565         }
1566 }
1567
1568 #define SET_ENTRY(entry, str) \
1569 { \
1570         if (str && *str) \
1571                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1572 }
1573
1574 #define SET_ADDRESS(type, str) \
1575 { \
1576         if (str && *str) \
1577                 compose_entry_append(compose, str, type); \
1578 }
1579
1580 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1581 {
1582         g_return_if_fail(msginfo != NULL);
1583
1584         SET_ENTRY(subject_entry, msginfo->subject);
1585         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1586         SET_ADDRESS(COMPOSE_CC, compose->cc);
1587         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1588         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1589
1590 #if 0 /* NEW COMPOSE GUI */
1591         if (compose->bcc) {
1592                 GtkItemFactory *ifactory;
1593                 GtkWidget *menuitem;
1594
1595                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1596                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
1597                 gtk_check_menu_item_set_active
1598                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1599         }
1600         if (compose->replyto) {
1601                 GtkItemFactory *ifactory;
1602                 GtkWidget *menuitem;
1603
1604                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1605                 menuitem = gtk_item_factory_get_item
1606                         (ifactory, "/Message/Reply to");
1607                 gtk_check_menu_item_set_active
1608                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1609         }
1610 #endif
1611 }
1612
1613 #undef SET_ENTRY
1614 #undef SET_ADDRESS
1615
1616 static void compose_exec_sig(Compose *compose, gchar *sigfile)
1617 {
1618         FILE *tmpfp;
1619         pid_t thepid;
1620         gchar *sigtext;
1621         FILE  *sigprg;
1622         gchar  *buf;
1623         size_t buf_len = 128;
1624  
1625         if (strlen(sigfile) < 2)
1626           return;
1627  
1628         sigprg = popen(sigfile+1, "r");
1629         if (sigprg) {
1630
1631                 buf = g_malloc(buf_len);
1632
1633                 if (!buf) {
1634                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1635                         "Unable to insert signature (malloc failed)\n", -1);
1636
1637                         pclose(sigprg);
1638                         return;
1639                 }
1640
1641                 while (!feof(sigprg)) {
1642                         bzero(buf, buf_len);
1643                         fread(buf, buf_len-1, 1, sigprg);
1644                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, buf, -1);
1645                 }
1646
1647                 g_free(buf);
1648                 pclose(sigprg);
1649         }
1650         else
1651         {
1652                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1653                 "Can't exec file: ", -1);
1654                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1655                 sigfile+1, -1);
1656         }
1657 }
1658
1659 static void compose_insert_sig(Compose *compose)
1660 {
1661         gchar *sigfile;
1662
1663         if (compose->account && compose->account->sig_path)
1664                 sigfile = g_strdup(compose->account->sig_path);
1665         else {
1666                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1667                                       DEFAULT_SIGNATURE, NULL);
1668         }
1669
1670         if (!is_file_or_fifo_exist(sigfile) & (sigfile[0] != '|')) {
1671                 g_free(sigfile);
1672                 return;
1673         }
1674
1675         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1676         if (prefs_common.sig_sep) {
1677                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1678                                 prefs_common.sig_sep, -1);
1679                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1680                                 "\n", 1);
1681         }
1682
1683         if (sigfile[0] == '|')
1684         {
1685                 compose_exec_sig(compose, sigfile);
1686         }
1687         else
1688         {
1689                 compose_insert_file(compose, sigfile);
1690         }
1691         g_free(sigfile);
1692 }
1693
1694 static void compose_insert_file(Compose *compose, const gchar *file)
1695 {
1696         GtkSText *text = GTK_STEXT(compose->text);
1697         gchar buf[BUFFSIZE];
1698         gint len;
1699         FILE *fp;
1700
1701         g_return_if_fail(file != NULL);
1702
1703         if ((fp = fopen(file, "r")) == NULL) {
1704                 FILE_OP_ERROR(file, "fopen");
1705                 return;
1706         }
1707
1708         gtk_stext_freeze(text);
1709
1710         while (fgets(buf, sizeof(buf), fp) != NULL) {
1711                 /* Strip <CR> if DOS/Windoze file, replace <CR> with <LF> if MAC file */
1712                 len = strlen(buf);
1713                 if (len > 1 && buf[len - 2] == '\r' && buf[len - 1] == '\n') {
1714                         buf[len - 2] = '\n';
1715                         buf[len - 1] = '\0';
1716                 } else {
1717                         while (--len > 0)
1718                                 if (buf[len] == '\r')
1719                                         buf[len] = '\n';
1720                 }
1721
1722                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1723         }
1724
1725         gtk_stext_thaw(text);
1726
1727         fclose(fp);
1728 }
1729
1730 static void compose_attach_info(Compose * compose, AttachInfo * ainfo,
1731                                 ContentType cnttype)
1732 {
1733         gchar *text[N_ATTACH_COLS];
1734         gint row;
1735
1736         text[COL_MIMETYPE] = ainfo->content_type;
1737         text[COL_SIZE] = to_human_readable(ainfo->size);
1738         text[COL_NAME] = ainfo->name;
1739
1740         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1741         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1742
1743         if (cnttype != MIME_MESSAGE_RFC822)
1744                 compose_changed_cb(NULL, compose);
1745 }
1746
1747 static void compose_attach_append_with_type(Compose *compose,
1748                                             const gchar *file,
1749                                             const gchar *type,
1750                                             ContentType cnttype)
1751 {
1752         AttachInfo *ainfo;
1753         off_t size;
1754
1755         if (!is_file_exist(file)) {
1756                 g_warning(_("File %s doesn't exist\n"), file);
1757                 return;
1758         }
1759         if ((size = get_file_size(file)) < 0) {
1760                 g_warning(_("Can't get file size of %s\n"), file);
1761                 return;
1762         }
1763         if (size == 0) {
1764                 alertpanel_notice(_("File %s is empty\n"), file);
1765                 return;
1766         }
1767 #if 0 /* NEW COMPOSE GUI */
1768         if (!compose->use_attach) {
1769                 GtkItemFactory *ifactory;
1770                 GtkWidget *menuitem;
1771
1772                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1773                 menuitem = gtk_item_factory_get_item(ifactory,
1774                                                      "/Message/Attach");
1775                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1776                                                TRUE);
1777         }
1778 #endif
1779         ainfo = g_new0(AttachInfo, 1);
1780         ainfo->file = g_strdup(file);
1781
1782         if (cnttype == MIME_MESSAGE_RFC822) {
1783                 ainfo->encoding = ENC_7BIT;
1784                 ainfo->name = g_strdup_printf(_("Message: %s"),
1785                                               g_basename(file));
1786         } else {
1787                 ainfo->encoding = ENC_BASE64;
1788                 ainfo->name = g_strdup(g_basename(file));
1789         }
1790
1791         ainfo->content_type = g_strdup(type);
1792         ainfo->size = size;
1793
1794         compose_attach_info(compose, ainfo, cnttype);
1795 }
1796
1797 static void compose_attach_append(Compose *compose, const gchar *file,
1798                                   ContentType cnttype)
1799 {
1800         AttachInfo *ainfo;
1801         gchar *text[N_ATTACH_COLS];
1802         off_t size;
1803         gint row;
1804
1805         if (!is_file_exist(file)) {
1806                 g_warning(_("File %s doesn't exist\n"), file);
1807                 return;
1808         }
1809         if ((size = get_file_size(file)) < 0) {
1810                 g_warning(_("Can't get file size of %s\n"), file);
1811                 return;
1812         }
1813         if (size == 0) {
1814                 alertpanel_notice(_("File %s is empty\n"), file);
1815                 return;
1816         }
1817 #if 0 /* NEW COMPOSE GUI */
1818         if (!compose->use_attach) {
1819                 GtkItemFactory *ifactory;
1820                 GtkWidget *menuitem;
1821
1822                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1823                 menuitem = gtk_item_factory_get_item(ifactory,
1824                                                      "/Message/Attach");
1825                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1826                                                TRUE);
1827         }
1828 #endif
1829         ainfo = g_new0(AttachInfo, 1);
1830         ainfo->file = g_strdup(file);
1831
1832         if (cnttype == MIME_MESSAGE_RFC822) {
1833                 ainfo->content_type = g_strdup("message/rfc822");
1834                 ainfo->encoding = ENC_7BIT;
1835                 ainfo->name = g_strdup_printf(_("Message: %s"),
1836                                               g_basename(file));
1837         } else {
1838                 ainfo->content_type = procmime_get_mime_type(file);
1839                 if (!ainfo->content_type)
1840                         ainfo->content_type =
1841                                 g_strdup("application/octet-stream");
1842                 ainfo->encoding = ENC_BASE64;
1843                 ainfo->name = g_strdup(g_basename(file));
1844         }
1845         ainfo->size = size;
1846
1847         compose_attach_info(compose, ainfo, cnttype);
1848 }
1849
1850 static void compose_wrap_line(Compose *compose)
1851 {
1852         GtkSText *text = GTK_STEXT(compose->text);
1853         gint ch_len, last_ch_len;
1854         gchar cbuf[MB_LEN_MAX], last_ch;
1855         guint text_len;
1856         guint line_end;
1857         guint quoted;
1858         gint p_start, p_end;
1859         gint line_pos, cur_pos;
1860         gint line_len, cur_len;
1861
1862 #define GET_STEXT(pos)                                                        \
1863         if (text->use_wchar)                                                 \
1864                 ch_len = wctomb(cbuf, (wchar_t)GTK_STEXT_INDEX(text, (pos))); \
1865         else {                                                               \
1866                 cbuf[0] = GTK_STEXT_INDEX(text, (pos));                       \
1867                 ch_len = 1;                                                  \
1868         }
1869
1870         gtk_stext_freeze(text);
1871
1872         text_len = gtk_stext_get_length(text);
1873
1874         /* check to see if the point is on the paragraph mark (empty line). */
1875         cur_pos = gtk_stext_get_point(text);
1876         GET_STEXT(cur_pos);
1877         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
1878                 if (cur_pos == 0)
1879                         goto compose_end; /* on the paragraph mark */
1880                 GET_STEXT(cur_pos - 1);
1881                 if (ch_len == 1 && *cbuf == '\n')
1882                         goto compose_end; /* on the paragraph mark */
1883         }
1884
1885         /* find paragraph start. */
1886         line_end = quoted = 0;
1887         for (p_start = cur_pos; p_start >= 0; --p_start) {
1888                 GET_STEXT(p_start);
1889                 if (ch_len == 1 && *cbuf == '\n') {
1890                         if (quoted)
1891                                 goto compose_end; /* quoted part */
1892                         if (line_end) {
1893                                 p_start += 2;
1894                                 break;
1895                         }
1896                         line_end = 1;
1897                 } else {
1898                         if (ch_len == 1 && strchr(">:#", *cbuf))
1899                                 quoted = 1;
1900                         else if (ch_len != 1 || !isspace(*cbuf))
1901                                 quoted = 0;
1902
1903                         line_end = 0;
1904                 }
1905         }
1906         if (p_start < 0)
1907                 p_start = 0;
1908
1909         /* find paragraph end. */
1910         line_end = 0;
1911         for (p_end = cur_pos; p_end < text_len; p_end++) {
1912                 GET_STEXT(p_end);
1913                 if (ch_len == 1 && *cbuf == '\n') {
1914                         if (line_end) {
1915                                 p_end -= 1;
1916                                 break;
1917                         }
1918                         line_end = 1;
1919                 } else {
1920                         if (line_end && ch_len == 1 && strchr(">:#", *cbuf))
1921                                 goto compose_end; /* quoted part */
1922
1923                         line_end = 0;
1924                 }
1925         }
1926         if (p_end >= text_len)
1927                 p_end = text_len;
1928
1929         if (p_start >= p_end)
1930                 goto compose_end;
1931
1932         line_len = cur_len = 0;
1933         last_ch_len = 0;
1934         last_ch = '\0';
1935         line_pos = p_start;
1936         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
1937                 guint space = 0;
1938
1939                 GET_STEXT(cur_pos);
1940
1941                 if (ch_len < 0) {
1942                         cbuf[0] = '\0';
1943                         ch_len = 1;
1944                 }
1945
1946                 if (ch_len == 1 && isspace(*cbuf))
1947                         space = 1;
1948
1949                 if (ch_len == 1 && *cbuf == '\n') {
1950                         guint replace = 0;
1951                         if (last_ch_len == 1 && !isspace(last_ch)) {
1952                                 if (cur_pos + 1 < p_end) {
1953                                         GET_STEXT(cur_pos + 1);
1954                                         if (ch_len == 1 && !isspace(*cbuf))
1955                                                 replace = 1;
1956                                 }
1957                         }
1958                         gtk_stext_set_point(text, cur_pos + 1);
1959                         gtk_stext_backward_delete(text, 1);
1960                         if (replace) {
1961                                 gtk_stext_set_point(text, cur_pos);
1962                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
1963                                 space = 1;
1964                         }
1965                         else {
1966                                 p_end--;
1967                                 cur_pos--;
1968                                 continue;
1969                         }
1970                 }
1971
1972                 last_ch_len = ch_len;
1973                 last_ch = *cbuf;
1974
1975                 if (space) {
1976                         line_pos = cur_pos + 1;
1977                         line_len = cur_len + ch_len;
1978                 }
1979
1980                 if (cur_len + ch_len > prefs_common.linewrap_len &&
1981                     line_len > 0) {
1982                         gint tlen = ch_len;
1983
1984                         GET_STEXT(line_pos - 1);
1985                         if (ch_len == 1 && isspace(*cbuf)) {
1986                                 gtk_stext_set_point(text, line_pos);
1987                                 gtk_stext_backward_delete(text, 1);
1988                                 p_end--;
1989                                 cur_pos--;
1990                                 line_pos--;
1991                                 cur_len--;
1992                                 line_len--;
1993                         }
1994                         ch_len = tlen;
1995
1996                         gtk_stext_set_point(text, line_pos);
1997                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
1998                         p_end++;
1999                         cur_pos++;
2000                         line_pos++;
2001                         cur_len = cur_len - line_len + ch_len;
2002                         line_len = 0;
2003                         continue;
2004                 }
2005
2006                 if (ch_len > 1) {
2007                         line_pos = cur_pos + 1;
2008                         line_len = cur_len + ch_len;
2009                 }
2010                 cur_len += ch_len;
2011         }
2012
2013 compose_end:
2014         gtk_stext_thaw(text);
2015
2016 #undef GET_STEXT
2017 }
2018
2019 /* return indent length */
2020 static guint get_indent_length(GtkSText *text, guint start_pos,
2021                                guint text_len) {
2022         gint indent_len = 0;
2023         gint i, ch_len;
2024         gchar cbuf[MB_CUR_MAX];
2025
2026         for (i = start_pos; i < text_len; i++) {
2027                 if (text->use_wchar)
2028                         ch_len = wctomb
2029                                 (cbuf, (wchar_t)GTK_STEXT_INDEX(text, i));
2030                 else {
2031                         cbuf[0] = GTK_STEXT_INDEX(text, i);
2032                         ch_len = 1;
2033                 }
2034                 if (ch_len > 1)
2035                         break;
2036                 /* allow space, tab, > or | */
2037                 if (cbuf[0] != ' ' && cbuf[0] != '\t' &&
2038                     cbuf[0] != '>' && cbuf[0] != '|')
2039                         break;
2040                 indent_len++;
2041         }
2042
2043         return indent_len;
2044 }
2045
2046 /* insert quotation string when line was wrapped, we know these
2047    are single byte characters */
2048 static guint ins_quote(GtkSText *text, guint quote_len, guint indent_len,
2049                        guint prev_line_pos, guint text_len,
2050                        gchar *quote_fmt) {
2051         guint i, ins_len;
2052         gchar ch;
2053
2054         if (indent_len) {
2055                 for (i = 0; i < indent_len; i++) {
2056                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2057                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2058                 }
2059                 ins_len = indent_len;
2060         }
2061         else {
2062                 gtk_stext_insert(text, NULL, NULL, NULL, quote_fmt, quote_len);
2063                 ins_len = quote_len;
2064         }
2065
2066         return ins_len;
2067 }
2068
2069 #undef WRAP_DEBUG
2070 #ifdef WRAP_DEBUG
2071 /* Darko: used when I debug wrapping */
2072 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2073 {
2074     int i;
2075     char ch;
2076
2077     printf("%d [", pos);
2078     for (i = pos; i < tlen; i++)
2079     {
2080         ch = GTK_STEXT_INDEX(text, i);
2081         if (breakoncr && ch == '\n')
2082             break;
2083         printf("%c", ch);
2084     }
2085     printf("]\n");
2086 }
2087 #endif
2088
2089 static void compose_wrap_line_all(Compose *compose)
2090 {
2091         GtkSText *text = GTK_STEXT(compose->text);
2092         guint tlen;
2093         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2094         gint line_len = 0, cur_len = 0;
2095         gint ch_len;
2096         gint is_new_line = 1, do_delete = 0;
2097         guint qlen = 0, i_len = 0;
2098         guint linewrap_quote = prefs_common.linewrap_quote;
2099         guint linewrap_len = prefs_common.linewrap_len;
2100         gchar *qfmt = prefs_common.quotemark;
2101         gchar cbuf[MB_LEN_MAX];
2102
2103         gtk_stext_freeze(text);
2104
2105         /* make text buffer contiguous */
2106         gtk_stext_compact_buffer(text);
2107
2108         tlen = gtk_stext_get_length(text);
2109
2110         for (; cur_pos < tlen; cur_pos++) {
2111                 /* mark position of new line - needed for quotation wrap */
2112                 if (linewrap_quote && is_new_line) {
2113                         qlen = gtkstext_str_strcmp(text, cur_pos, tlen, qfmt);
2114                         is_new_line = 0;
2115                         if (qlen) {
2116                                 i_len = get_indent_length(text, cur_pos, tlen);
2117                         }
2118                         else
2119                                 i_len = 0;
2120                         p_pos = cur_pos;
2121 #ifdef WRAP_DEBUG
2122                         printf("new line i_len=%d qlen=%d p_pos=", i_len, qlen);
2123                         dump_text(text, p_pos, tlen, 1);
2124 #endif
2125                 }
2126
2127                 /* get character(s) at current position */
2128                 if (text->use_wchar)
2129                         ch_len = wctomb
2130                                 (cbuf, (wchar_t)GTK_STEXT_INDEX(text, cur_pos));
2131                 else {
2132                         cbuf[0] = GTK_STEXT_INDEX(text, cur_pos);
2133                         ch_len = 1;
2134                 }
2135
2136                 /* fix line length for tabs */
2137                 if (ch_len == 1 && *cbuf == '\t') {
2138                         guint tab_width = text->default_tab_width;
2139                         guint tab_offset = line_len % tab_width;
2140
2141 #ifdef WRAP_DEBUG
2142                         printf("found tab at pos=%d line_len=%d ", cur_pos,
2143                                 line_len);
2144 #endif
2145                         if (tab_offset) {
2146                                 line_len += tab_width - tab_offset - 1;
2147                                 cur_len = line_len;
2148                         }
2149 #ifdef WRAP_DEBUG
2150                         printf("new_len=%d\n", line_len);
2151 #endif
2152                 }
2153
2154                 /* we have encountered line break */
2155                 if (ch_len == 1 && *cbuf == '\n') {
2156                         gint clen;
2157                         guint ilen;
2158                         gchar cb[MB_CUR_MAX];
2159
2160 #ifdef WRAP_DEBUG
2161                         printf("found CR at %d\n", cur_pos);
2162 #endif
2163                         /* if it's just quotation + newline skip it */
2164                         if (i_len && (cur_pos + 1 < tlen)) {
2165                                 /* check if text at new line matches indent */
2166                                 ilen =  gtkstext_strncmp(text, cur_pos + 1,
2167                                                          p_pos, i_len, tlen);
2168                                 if (cur_pos + ilen < tlen) {
2169                                         if (text->use_wchar)
2170                                                 clen = wctomb(cb, (wchar_t)GTK_STEXT_INDEX(text, cur_pos + ilen + 1));
2171                                         else {
2172                                                 cb[0] = GTK_STEXT_INDEX(text,
2173                                                             cur_pos + ilen + 1);
2174                                                 clen = 1;
2175                                         }
2176                                         /* no need to join the lines */
2177                                         if ((clen == 1) && (cb[0] == '\n'))
2178                                                 do_delete = 0;
2179                                 }
2180                         }
2181
2182 #ifdef WRAP_DEBUG
2183                         printf("qlen=%d l_len=%d wrap_len=%d do_del=%d\n",
2184                                 qlen, line_len, linewrap_len, do_delete);
2185 #endif
2186                         /* should we delete to perform smart wrapping */
2187                         if (qlen && line_len < linewrap_len && do_delete) {
2188                                 /* get rid of newline */
2189                                 gtk_stext_set_point(text, cur_pos);
2190                                 gtk_stext_forward_delete(text, 1);
2191                                 tlen--;
2192
2193                                 /* if text starts with quote fmt or with
2194                                    indent string, delete them */
2195                                 if (i_len) {
2196                                         ilen =  gtkstext_strncmp(text, cur_pos,
2197                                                                  p_pos, i_len,
2198                                                                  tlen);
2199                                         if (ilen) {
2200                                                 gtk_stext_forward_delete(text,
2201                                                                          ilen);
2202                                                 tlen -= ilen;
2203                                         }
2204                                 }
2205                                 else if (qlen) {
2206                                         if (gtkstext_str_strcmp(text, cur_pos,
2207                                                                 tlen, qfmt)) {
2208                                                 gtk_stext_forward_delete(text,
2209                                                                  qlen);
2210                                                 tlen -= qlen;
2211                                         }
2212                                 }
2213
2214                                 if (text->use_wchar)
2215                                         clen = wctomb
2216                                                 (cb, (wchar_t)GTK_STEXT_INDEX(text, cur_pos));
2217                                 else {
2218                                         cb[0] = GTK_STEXT_INDEX(text, cur_pos);
2219                                         clen = 1;
2220                                 }
2221
2222                                 /* insert space if it's alphanumeric */
2223                                 if ((cur_pos != line_pos) &&
2224                                     ((clen > 1) || isalnum(cb[0]))) {
2225                                         gtk_stext_insert(text, NULL, NULL,
2226                                                          NULL, " ", 1);
2227                                         gtk_stext_compact_buffer(text);
2228                                         tlen++;
2229                                 }
2230
2231                                 /* and start over with current line */
2232                                 cur_pos = p_pos - 1;
2233                                 line_pos = cur_pos;
2234                                 line_len = cur_len = 0;
2235                                 qlen = 0;
2236                                 do_delete = 0;
2237                                 is_new_line = 1;
2238 #ifdef WRAP_DEBUG
2239                                 printf("after delete l_pos=");
2240                                 dump_text(text, line_pos, tlen, 1);
2241 #endif
2242                                 continue;
2243                         }
2244
2245                         /* mark new line beginning */
2246                         line_pos = cur_pos + 1;
2247                         line_len = cur_len = 0;
2248                         qlen = 0;
2249                         do_delete = 0;
2250                         is_new_line = 1;
2251                         continue;
2252                 }
2253
2254                 if (ch_len < 0) {
2255                         cbuf[0] = '\0';
2256                         ch_len = 1;
2257                 }
2258
2259                 /* possible line break */
2260                 if (ch_len == 1 && isspace(*cbuf)) {
2261                         line_pos = cur_pos + 1;
2262                         line_len = cur_len + ch_len;
2263                 }
2264
2265                 /* are we over wrapping length set in preferences ? */
2266                 if (cur_len + ch_len > linewrap_len) {
2267                         gint clen;
2268
2269 #ifdef WRAP_DEBUG
2270                         printf("should wrap cur_pos=%d ", cur_pos);
2271                         dump_text(text, p_pos, tlen, 1);
2272                         dump_text(text, line_pos, tlen, 1);
2273 #endif
2274                         /* force wrapping if it is one long word but not URL */
2275                         if (p_pos + i_len == line_pos)
2276                                 if (!is_url_string(text, line_pos, tlen))
2277                                         line_pos = cur_pos - 1;
2278 #ifdef WRAP_DEBUG
2279                         printf("new line_pos=%d\n", line_pos);
2280 #endif
2281
2282                         /* if next character is space delete it */
2283                         if (text->use_wchar)
2284                                 clen = wctomb(cbuf, (wchar_t)GTK_STEXT_INDEX(text, line_pos - 1));
2285                         else {
2286                                 cbuf[0] = GTK_STEXT_INDEX(text, line_pos - 1);
2287                                 clen = 1;
2288                         }
2289                         if (clen == 1 && isspace(*cbuf)) {
2290                                 if (p_pos + i_len != line_pos ||
2291                                     !is_url_string(text, line_pos, tlen)) {
2292                                         gtk_stext_set_point(text, line_pos);
2293                                         gtk_stext_backward_delete(text, 1);
2294                                         tlen--;
2295                                         cur_pos--;
2296                                         line_pos--;
2297                                         cur_len--;
2298                                         line_len--;
2299                                 }
2300                         }
2301
2302                         /* if it is URL at beginning of line don't wrap */
2303                         if (p_pos + i_len == line_pos &&
2304                             is_url_string(text, line_pos, tlen)) {
2305 #ifdef WRAP_DEBUG
2306                                 printf("found URL at ");
2307                                 dump_text(text, line_pos, tlen, 1);
2308 #endif
2309                                 continue;
2310                         }
2311
2312                         /* insert CR */
2313                         gtk_stext_set_point(text, line_pos);
2314                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2315                         gtk_stext_compact_buffer(text);
2316                         tlen++;
2317                         cur_pos++;
2318                         line_pos++;
2319                         cur_len = cur_len - line_len + ch_len;
2320                         line_len = 0;
2321 #ifdef WRAP_DEBUG
2322                         printf("after CR insert ");
2323                         dump_text(text, line_pos, tlen, 1);
2324 #endif
2325
2326                         /* should we insert quotation ? */
2327                         if (linewrap_quote && qlen) {
2328                                 /* only if line is not already quoted  */
2329                                 if (!gtkstext_str_strcmp(text, line_pos,
2330                                                          tlen, qfmt)) {
2331                                         guint ins_len;
2332
2333                                         if (line_pos - p_pos > i_len) {
2334                                                 ins_len = ins_quote(text,
2335                                                                     qlen,
2336                                                                     i_len,
2337                                                                     p_pos,
2338                                                                     tlen,
2339                                                                     qfmt);
2340
2341                                                 gtk_stext_compact_buffer(text);
2342                                                 tlen += ins_len;
2343                                         }
2344
2345                                         /* for loop will increase it */
2346                                         cur_pos = line_pos - 1;
2347                                         cur_len = 0;
2348                                         line_len = 0;
2349                                         /* start over with current line */
2350                                         is_new_line = 1;
2351                                         do_delete = 1;
2352 #ifdef WRAP_DEBUG
2353                                         printf("after quote insert ");
2354                                         dump_text(text, line_pos, tlen, 1);
2355 #endif
2356                                 }
2357                         }
2358                         continue;
2359                 }
2360
2361                 if (ch_len > 1) {
2362                         line_pos = cur_pos + 1;
2363                         line_len = cur_len + ch_len;
2364                 }
2365                 /* advance to next character in buffer */
2366                 cur_len += ch_len;
2367         }
2368
2369         gtk_stext_thaw(text);
2370 }
2371
2372 static void compose_set_title(Compose *compose)
2373 {
2374         gchar *str;
2375         gchar *edited;
2376
2377         edited = compose->modified ? _(" [Edited]") : "";
2378         if (compose->account && compose->account->address)
2379                 str = g_strdup_printf(_("%s - Compose message%s"),
2380                                       compose->account->address, edited);
2381         else
2382                 str = g_strdup_printf(_("Compose message%s"), edited);
2383         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2384         g_free(str);
2385 }
2386
2387 /**
2388  * compose_current_mail_account:
2389  * 
2390  * Find a current mail account (the currently selected account, or the
2391  * default account, if a news account is currently selected).  If a
2392  * mail account cannot be found, display an error message.
2393  * 
2394  * Return value: Mail account, or NULL if not found.
2395  **/
2396 static PrefsAccount *
2397 compose_current_mail_account(void)
2398 {
2399         PrefsAccount *ac;
2400
2401         if (cur_account && cur_account->protocol != A_NNTP)
2402                 ac = cur_account;
2403         else {
2404                 ac = account_get_default();
2405                 if (!ac || ac->protocol == A_NNTP) {
2406                         alertpanel_error(_("Account for sending mail is not specified.\n"
2407                                            "Please select a mail account before sending."));
2408                         return NULL;
2409                 }
2410         }
2411         return ac;
2412 }
2413
2414 gboolean compose_check_for_valid_recipient(Compose *compose) {
2415         gchar *recipient_headers[] = {"To:", "Newsgroups:", "Cc:", "Bcc:", NULL};
2416         gboolean recipient_found = FALSE;
2417         GSList *list;
2418         gchar **strptr;
2419
2420         for(list = compose->header_list; list; list = list->next) {
2421                 gchar *header;
2422                 gchar *entry;
2423                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(((compose_headerentry *)list->data)->combo)->entry));
2424                 entry = gtk_editable_get_chars(GTK_EDITABLE(((compose_headerentry *)list->data)->entry), 0, -1);
2425                 g_strstrip(entry);
2426                 if(entry[0] != '\0') {
2427                         for(strptr = recipient_headers; *strptr != NULL; strptr++) {
2428                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2429                                         recipient_found = TRUE;
2430                                 }
2431                         }
2432                 }
2433                 g_free(entry);
2434         }
2435         return recipient_found;
2436 }
2437
2438 gint compose_send(Compose *compose)
2439 {
2440         gchar tmp[MAXPATHLEN + 1];
2441         gint ok = 0;
2442         static gboolean lock = FALSE;
2443
2444         if (lock) return 1;
2445
2446         g_return_val_if_fail(compose->account != NULL, -1);
2447         g_return_val_if_fail(compose->orig_account != NULL, -1);
2448
2449         lock = TRUE;
2450
2451         if(!compose_check_for_valid_recipient(compose)) {
2452                 alertpanel_error(_("Recipient is not specified."));
2453                 lock = FALSE;
2454                 return 1;
2455         }
2456
2457         /* write to temporary file */
2458         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
2459                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
2460
2461         if (prefs_common.linewrap_at_send)
2462                 compose_wrap_line_all(compose);
2463
2464         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2465                 lock = FALSE;
2466                 return -1;
2467         }
2468
2469         if (!compose->to_list && !compose->newsgroup_list) {
2470                 g_warning(_("can't get recipient list."));
2471                 unlink(tmp);
2472                 lock = FALSE;
2473                 return -1;
2474         }
2475
2476         if (compose->to_list) {
2477                 PrefsAccount *ac;
2478
2479 #if 0 /* NEW COMPOSE GUI */
2480                 if (compose->account->protocol != A_NNTP)
2481                         ac = compose->account;
2482                 else if (compose->orig_account->protocol != A_NNTP)
2483                         ac = compose->orig_account;
2484                 else if (cur_account && cur_account->protocol != A_NNTP)
2485                         ac = cur_account;
2486                 else {
2487                         ac = compose_current_mail_account();
2488                         if (!ac) {
2489                                 unlink(tmp);
2490                                 lock = FALSE;
2491                                 return -1;
2492                         }
2493                 }
2494 #endif
2495                 ac = compose->account;
2496
2497                 ok = send_message(tmp, ac, compose->to_list);
2498                 statusbar_pop_all();
2499         }
2500
2501         if (ok == 0 && compose->newsgroup_list) {
2502                 Folder *folder;
2503
2504                 if (compose->account->protocol == A_NNTP)
2505                         folder = FOLDER(compose->account->folder);
2506                 else
2507                         folder = FOLDER(compose->orig_account->folder);
2508
2509                 ok = news_post(folder, tmp);
2510                 if (ok < 0) {
2511                         alertpanel_error(_("Error occurred while posting the message to %s ."),
2512                                          compose->account->nntp_server);
2513                         unlink(tmp);
2514                         lock = FALSE;
2515                         return -1;
2516                 }
2517         }
2518
2519         /* queue message if failed to send */
2520         if (ok < 0) {
2521                 if (prefs_common.queue_msg) {
2522                         AlertValue val;
2523
2524                         val = alertpanel
2525                                 (_("Queueing"),
2526                                  _("Error occurred while sending the message.\n"
2527                                    "Put this message into queue folder?"),
2528                                  _("OK"), _("Cancel"), NULL);
2529                         if (G_ALERTDEFAULT == val) {
2530                                 ok = compose_queue(compose, tmp);
2531                                 if (ok < 0)
2532                                         alertpanel_error(_("Can't queue the message."));
2533                         }
2534                 } else
2535                         alertpanel_error(_("Error occurred while sending the message."));
2536         } else {
2537                 if (compose->mode == COMPOSE_REEDIT) {
2538                         compose_remove_reedit_target(compose);
2539                         if (compose->targetinfo)
2540                                 folderview_update_item
2541                                         (compose->targetinfo->folder, TRUE);
2542                 }
2543         }
2544
2545         /* save message to outbox */
2546         if (ok == 0 && prefs_common.savemsg) {
2547                 if (compose_save_to_outbox(compose, tmp) < 0)
2548                         alertpanel_error
2549                                 (_("Can't save the message to outbox."));
2550         }
2551
2552         unlink(tmp);
2553         lock = FALSE;
2554         return ok;
2555 }
2556
2557 static gboolean compose_use_attach(Compose *compose) {
2558     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
2559 }
2560
2561 static gint compose_write_to_file(Compose *compose, const gchar *file,
2562                                   gboolean is_draft)
2563 {
2564         FILE *fp;
2565         size_t len;
2566         gchar *chars;
2567         gchar *buf;
2568         const gchar *out_codeset;
2569         EncodingType encoding;
2570
2571         if ((fp = fopen(file, "w")) == NULL) {
2572                 FILE_OP_ERROR(file, "fopen");
2573                 return -1;
2574         }
2575
2576         /* chmod for security */
2577         if (change_file_mode_rw(fp, file) < 0) {
2578                 FILE_OP_ERROR(file, "chmod");
2579                 g_warning(_("can't change file mode\n"));
2580         }
2581
2582         /* get all composed text */
2583         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2584         len = strlen(chars);
2585         if (is_ascii_str(chars)) {
2586                 buf = g_strdup(chars);
2587                 out_codeset = CS_US_ASCII;
2588                 encoding = ENC_7BIT;
2589         } else {
2590                 const gchar *src_codeset;
2591
2592                 out_codeset = conv_get_outgoing_charset_str();
2593                 if (!strcasecmp(out_codeset, CS_US_ASCII))
2594                         out_codeset = CS_ISO_8859_1;
2595                 encoding = procmime_get_encoding_for_charset(out_codeset);
2596
2597                 src_codeset = conv_get_current_charset_str();
2598                 /* if current encoding is US-ASCII, set it the same as
2599                    outgoing one to prevent code conversion failure */
2600                 if (!strcasecmp(src_codeset, CS_US_ASCII))
2601                         src_codeset = out_codeset;
2602
2603                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
2604                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
2605
2606                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
2607                 if (!buf) {
2608                         g_free(chars);
2609                         fclose(fp);
2610                         unlink(file);
2611                         alertpanel_error(_("Can't convert the codeset of the message."));
2612                         return -1;
2613                 }
2614         }
2615         g_free(chars);
2616
2617         /* write headers */
2618         if (compose_write_headers
2619                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
2620                 g_warning(_("can't write headers\n"));
2621                 fclose(fp);
2622                 /* unlink(file); */
2623                 g_free(buf);
2624                 return -1;
2625         }
2626
2627         if (compose_use_attach(compose)) {
2628 #if USE_GPGME
2629             /* This prolog message is ignored by mime software and
2630              * because it would make our signing/encryption task
2631              * tougher, we don't emit it in that case */
2632             if (!compose->use_signing && !compose->use_encryption)
2633 #endif
2634                 fputs("This is a multi-part message in MIME format.\n", fp);
2635
2636                 fprintf(fp, "\n--%s\n", compose->boundary);
2637                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
2638                         out_codeset);
2639                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
2640                         procmime_get_encoding_str(encoding));
2641                 fputc('\n', fp);
2642         }
2643
2644         /* write body */
2645         len = strlen(buf);
2646         if (encoding == ENC_BASE64) {
2647                 gchar outbuf[B64_BUFFSIZE];
2648                 gint i, l;
2649
2650                 for (i = 0; i < len; i += B64_LINE_SIZE) {
2651                         l = MIN(B64_LINE_SIZE, len - i);
2652                         to64frombits(outbuf, buf + i, l);
2653                         fputs(outbuf, fp);
2654                         fputc('\n', fp);
2655                 }
2656         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
2657                 FILE_OP_ERROR(file, "fwrite");
2658                 fclose(fp);
2659                 unlink(file);
2660                 g_free(buf);
2661                 return -1;
2662         }
2663         g_free(buf);
2664
2665         if (compose_use_attach(compose))
2666                 compose_write_attach(compose, fp);
2667
2668         if (fclose(fp) == EOF) {
2669                 FILE_OP_ERROR(file, "fclose");
2670                 unlink(file);
2671                 return -1;
2672         }
2673
2674 #if USE_GPGME
2675         if (compose->use_signing) {
2676                 if (rfc2015_sign(file, compose->account) < 0) {
2677                         unlink(file);
2678                         return -1;
2679                 }
2680         }
2681         if (compose->use_encryption) {
2682                 if (rfc2015_encrypt(file, compose->to_list) < 0) {
2683                         unlink(file);
2684                         return -1;
2685                 }
2686         }
2687 #endif /* USE_GPGME */
2688
2689         return 0;
2690 }
2691
2692 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
2693 {
2694         FILE *fp;
2695         size_t len;
2696         gchar *chars;
2697
2698         if ((fp = fopen(file, "w")) == NULL) {
2699                 FILE_OP_ERROR(file, "fopen");
2700                 return -1;
2701         }
2702
2703         /* chmod for security */
2704         if (change_file_mode_rw(fp, file) < 0) {
2705                 FILE_OP_ERROR(file, "chmod");
2706                 g_warning(_("can't change file mode\n"));
2707         }
2708
2709         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2710
2711         /* write body */
2712         len = strlen(chars);
2713         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
2714                 FILE_OP_ERROR(file, "fwrite");
2715                 g_free(chars);
2716                 fclose(fp);
2717                 unlink(file);
2718                 return -1;
2719         }
2720
2721         g_free(chars);
2722
2723         if (fclose(fp) == EOF) {
2724                 FILE_OP_ERROR(file, "fclose");
2725                 unlink(file);
2726                 return -1;
2727         }
2728         return 0;
2729 }
2730
2731 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
2732 {
2733         FolderItem *outbox;
2734         gchar *path;
2735         gint num;
2736         FILE *fp;
2737
2738         debug_print(_("saving sent message...\n"));
2739
2740         outbox = folder_get_default_outbox();
2741         path = folder_item_get_path(outbox);
2742         if (!is_dir_exist(path))
2743                 make_dir_hier(path);
2744
2745         folder_item_scan(outbox);
2746         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
2747                 g_free(path);
2748                 g_warning(_("can't save message\n"));
2749                 return -1;
2750         }
2751
2752         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
2753                 g_warning(_("can't open mark file\n"));
2754         else {
2755                 MsgInfo newmsginfo;
2756
2757                 newmsginfo.msgnum = num;
2758                 newmsginfo.flags.perm_flags = 0;
2759                 newmsginfo.flags.tmp_flags = 0;
2760                 procmsg_write_flags(&newmsginfo, fp);
2761                 fclose(fp);
2762         }
2763         g_free(path);
2764
2765         return 0;
2766 }
2767
2768 static gint compose_remove_reedit_target(Compose *compose)
2769 {
2770         FolderItem *item;
2771         MsgInfo *msginfo = compose->targetinfo;
2772
2773         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
2774         if (!msginfo) return -1;
2775
2776         item = msginfo->folder;
2777         g_return_val_if_fail(item != NULL, -1);
2778
2779         folder_item_scan(item);
2780         if (procmsg_msg_exist(msginfo) &&
2781             (item->stype == F_DRAFT || item->stype == F_QUEUE)) {
2782                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
2783                         g_warning(_("can't remove the old message\n"));
2784                         return -1;
2785                 }
2786         }
2787
2788         return 0;
2789 }
2790
2791 static gint compose_queue(Compose *compose, const gchar *file)
2792 {
2793         FolderItem *queue;
2794         gchar *tmp, *queue_path;
2795         FILE *fp, *src_fp;
2796         GSList *cur;
2797         gchar buf[BUFFSIZE];
2798         gint num;
2799
2800         debug_print(_("queueing message...\n"));
2801         g_return_val_if_fail(compose->to_list != NULL, -1);
2802         g_return_val_if_fail(compose->account != NULL, -1);
2803
2804         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
2805                               G_DIR_SEPARATOR, (gint)compose);
2806         if ((fp = fopen(tmp, "w")) == NULL) {
2807                 FILE_OP_ERROR(tmp, "fopen");
2808                 g_free(tmp);
2809                 return -1;
2810         }
2811         if ((src_fp = fopen(file, "r")) == NULL) {
2812                 FILE_OP_ERROR(file, "fopen");
2813                 fclose(fp);
2814                 unlink(tmp);
2815                 g_free(tmp);
2816                 return -1;
2817         }
2818         if (change_file_mode_rw(fp, tmp) < 0) {
2819                 FILE_OP_ERROR(tmp, "chmod");
2820                 g_warning(_("can't change file mode\n"));
2821         }
2822
2823         /* queueing variables */
2824         fprintf(fp, "AF:\n");
2825         fprintf(fp, "NF:0\n");
2826         fprintf(fp, "PS:10\n");
2827         fprintf(fp, "SRH:1\n");
2828         fprintf(fp, "SFN:\n");
2829         fprintf(fp, "DSR:\n");
2830         if (compose->msgid)
2831                 fprintf(fp, "MID:<%s>\n", compose->msgid);
2832         else
2833                 fprintf(fp, "MID:\n");
2834         fprintf(fp, "CFG:\n");
2835         fprintf(fp, "PT:0\n");
2836         fprintf(fp, "S:%s\n", compose->account->address);
2837         fprintf(fp, "RQ:\n");
2838         if (compose->account->smtp_server)
2839                 fprintf(fp, "SSV:%s\n", compose->account->smtp_server);
2840         else
2841                 fprintf(fp, "SSV:\n");
2842         if (compose->account->nntp_server)
2843                 fprintf(fp, "NSV:%s\n", compose->account->nntp_server);
2844         else
2845                 fprintf(fp, "NSV:\n");
2846         fprintf(fp, "SSH:\n");
2847         fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
2848         for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
2849                 fprintf(fp, ",<%s>", (gchar *)cur->data);
2850         fprintf(fp, "\n");
2851         /* Sylpheed account ID */
2852         fprintf(fp, "AID:%d\n", compose->account->account_id);
2853         fprintf(fp, "\n");
2854
2855         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2856                 if (fputs(buf, fp) == EOF) {
2857                         FILE_OP_ERROR(tmp, "fputs");
2858                         fclose(fp);
2859                         fclose(src_fp);
2860                         unlink(tmp);
2861                         g_free(tmp);
2862                         return -1;
2863                 }
2864         }
2865
2866         fclose(src_fp);
2867         if (fclose(fp) == EOF) {
2868                 FILE_OP_ERROR(tmp, "fclose");
2869                 unlink(tmp);
2870                 g_free(tmp);
2871                 return -1;
2872         }
2873
2874         queue = folder_get_default_queue();
2875
2876         folder_item_scan(queue);
2877         queue_path = folder_item_get_path(queue);
2878         if (!is_dir_exist(queue_path))
2879                 make_dir_hier(queue_path);
2880         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
2881                 g_warning(_("can't queue the message\n"));
2882                 unlink(tmp);
2883                 g_free(tmp);
2884                 g_free(queue_path);
2885                 return -1;
2886         }
2887         g_free(tmp);
2888
2889         if (compose->mode == COMPOSE_REEDIT) {
2890                 compose_remove_reedit_target(compose);
2891                 if (compose->targetinfo &&
2892                     compose->targetinfo->folder != queue)
2893                         folderview_update_item
2894                                 (compose->targetinfo->folder, TRUE);
2895         }
2896
2897         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
2898                 g_warning(_("can't open mark file\n"));
2899         else {
2900                 MsgInfo newmsginfo;
2901
2902                 newmsginfo.msgnum = num;
2903                 newmsginfo.flags.perm_flags = 0;
2904                 newmsginfo.flags.tmp_flags = 0;
2905                 procmsg_write_flags(&newmsginfo, fp);
2906                 fclose(fp);
2907         }
2908         g_free(queue_path);
2909
2910         folder_item_scan(queue);
2911         folderview_update_item(queue, TRUE);
2912
2913         return 0;
2914 }
2915
2916 static void compose_write_attach(Compose *compose, FILE *fp)
2917 {
2918         AttachInfo *ainfo;
2919         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2920         gint row;
2921         FILE *attach_fp;
2922         gchar filename[BUFFSIZE];
2923         gint len;
2924
2925         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
2926              row++) {
2927                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
2928                         g_warning(_("Can't open file %s\n"), ainfo->file);
2929                         continue;
2930                 }
2931
2932                 fprintf(fp, "\n--%s\n", compose->boundary);
2933
2934                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
2935                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
2936                         fprintf(fp, "Content-Disposition: inline\n");
2937                 } else {
2938                         conv_encode_header(filename, sizeof(filename),
2939                                            ainfo->name, 12);
2940                         fprintf(fp, "Content-Type: %s;\n"
2941                                     " name=\"%s\"\n",
2942                                 ainfo->content_type, filename);
2943                         fprintf(fp, "Content-Disposition: attachment;\n"
2944                                     " filename=\"%s\"\n", filename);
2945                 }
2946
2947                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
2948                         procmime_get_encoding_str(ainfo->encoding));
2949
2950                 if (ainfo->encoding == ENC_7BIT) {
2951                         gchar buf[BUFFSIZE];
2952
2953                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
2954                                 strcrchomp(buf);
2955                                 fputs(buf, fp);
2956                         }
2957                 } else {
2958                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
2959
2960                         while ((len = fread(inbuf, sizeof(gchar),
2961                                             B64_LINE_SIZE, attach_fp))
2962                                == B64_LINE_SIZE) {
2963                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
2964                                 fputs(outbuf, fp);
2965                                 fputc('\n', fp);
2966                         }
2967                         if (len > 0 && feof(attach_fp)) {
2968                                 to64frombits(outbuf, inbuf, len);
2969                                 fputs(outbuf, fp);
2970                                 fputc('\n', fp);
2971                         }
2972                 }
2973
2974                 fclose(attach_fp);
2975         }
2976
2977         fprintf(fp, "\n--%s--\n", compose->boundary);
2978 }
2979
2980 #define IS_IN_CUSTOM_HEADER(header) \
2981         (compose->account->add_customhdr && \
2982          custom_header_find(compose->account->customhdr_list, header) != NULL)
2983
2984 static gint compose_write_headers_from_headerlist(Compose *compose, 
2985                                                   FILE *fp, 
2986                                                   gchar *header,
2987                                                   GSList *(*list_append_func) (GSList *list, const gchar *str),
2988                                                   GSList **dest_list)
2989 {
2990         gchar buf[BUFFSIZE];
2991         gchar *str, *header_w_colon, *trans_hdr;
2992         gboolean first_address;
2993         GSList *list;
2994         compose_headerentry *headerentry;
2995
2996         if (IS_IN_CUSTOM_HEADER(header)) {
2997                 return 0;
2998         }
2999
3000         debug_print(_("Writing %s-header\n"), header);
3001
3002         header_w_colon = g_strconcat(header, ":", NULL);
3003         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3004
3005         first_address = TRUE;
3006         for(list = compose->header_list; list; list = list->next) {
3007                 headerentry = ((compose_headerentry *)list->data);
3008                 if(!strcmp(trans_hdr, gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)))) {
3009                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3010                         Xstrdup_a(str, str, return -1);
3011                         g_strstrip(str);
3012                         if(str[0] != '\0') {
3013                                 if(list_append_func)
3014                                         *dest_list = list_append_func(*dest_list, str);
3015                                 compose_convert_header
3016                                         (buf, sizeof(buf), str,
3017                                         strlen(header) + 2);
3018                                 if(first_address) {
3019                                         fprintf(fp, "%s: ", header);
3020                                         first_address = FALSE;
3021                                 } else {
3022                                         fprintf(fp, ", ");
3023                                 }
3024                                 fprintf(fp, "%s", buf);
3025                         }
3026                 }
3027         }
3028         if(!first_address) {
3029                 fprintf(fp, "\n");
3030         }
3031
3032         g_free(header_w_colon);
3033
3034         return(0);
3035 }
3036
3037 static gint compose_write_headers(Compose *compose, FILE *fp,
3038                                   const gchar *charset, EncodingType encoding,
3039                                   gboolean is_draft)
3040 {
3041         gchar buf[BUFFSIZE];
3042         gchar *str;
3043         /* struct utsname utsbuf; */
3044
3045         g_return_val_if_fail(fp != NULL, -1);
3046         g_return_val_if_fail(charset != NULL, -1);
3047         g_return_val_if_fail(compose->account != NULL, -1);
3048         g_return_val_if_fail(compose->account->address != NULL, -1);
3049
3050         /* Date */
3051         if (compose->account->add_date) {
3052                 get_rfc822_date(buf, sizeof(buf));
3053                 fprintf(fp, "Date: %s\n", buf);
3054         }
3055
3056         /* From */
3057         if (!IS_IN_CUSTOM_HEADER("From")) {
3058                 if (compose->account->name && *compose->account->name) {
3059                         compose_convert_header
3060                                 (buf, sizeof(buf), compose->account->name,
3061                                  strlen("From: "));
3062                         fprintf(fp, "From: %s <%s>\n",
3063                                 buf, compose->account->address);
3064                 } else
3065                         fprintf(fp, "From: %s\n", compose->account->address);
3066         }
3067         
3068         slist_free_strings(compose->to_list);
3069         g_slist_free(compose->to_list);
3070         compose->to_list = NULL;
3071
3072         /* To */
3073         compose_write_headers_from_headerlist(compose, fp, "To", address_list_append, &compose->to_list);
3074 #if 0 /* NEW COMPOSE GUI */
3075         if (compose->use_to) {
3076                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3077                 if (*str != '\0') {
3078                         Xstrdup_a(str, str, return -1);
3079                         g_strstrip(str);
3080                         if (*str != '\0') {
3081                                 compose->to_list = address_list_append
3082                                         (compose->to_list, str);
3083                                 if (!IS_IN_CUSTOM_HEADER("To")) {
3084                                         compose_convert_header
3085                                                 (buf, sizeof(buf), str,
3086                                                  strlen("To: "));
3087                                         fprintf(fp, "To: %s\n", buf);
3088                                 }
3089                         }
3090                 }
3091         }
3092 #endif
3093         slist_free_strings(compose->newsgroup_list);
3094         g_slist_free(compose->newsgroup_list);
3095         compose->newsgroup_list = NULL;
3096
3097         /* Newsgroups */
3098         compose_write_headers_from_headerlist(compose, fp, "Newsgroups", newsgroup_list_append, &compose->newsgroup_list);
3099 #if 0 /* NEW COMPOSE GUI */
3100         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3101         if (*str != '\0') {
3102                 Xstrdup_a(str, str, return -1);
3103                 g_strstrip(str);
3104                 remove_space(str);
3105                 if (*str != '\0') {
3106                         compose->newsgroup_list =
3107                                 newsgroup_list_append(compose->newsgroup_list,
3108                                                       str);
3109                         if (!IS_IN_CUSTOM_HEADER("Newsgroups")) {
3110                                 compose_convert_header(buf, sizeof(buf), str,
3111                                                        strlen("Newsgroups: "));
3112                                 fprintf(fp, "Newsgroups: %s\n", buf);
3113                         }
3114                 }
3115         }
3116 #endif
3117         /* Cc */
3118         compose_write_headers_from_headerlist(compose, fp, "Cc", address_list_append, &compose->to_list);
3119 #if 0 /* NEW COMPOSE GUI */
3120         if (compose->use_cc) {
3121                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
3122                 if (*str != '\0') {
3123                         Xstrdup_a(str, str, return -1);
3124                         g_strstrip(str);
3125                         if (*str != '\0') {
3126                                 compose->to_list = address_list_append
3127                                         (compose->to_list, str);
3128                                 if (!IS_IN_CUSTOM_HEADER("Cc")) {
3129                                         compose_convert_header
3130                                                 (buf, sizeof(buf), str,
3131                                                  strlen("Cc: "));
3132                                         fprintf(fp, "Cc: %s\n", buf);
3133                                 }
3134                         }
3135                 }
3136         }
3137 #endif
3138         /* Bcc */
3139         compose_write_headers_from_headerlist(compose, fp, "Bcc", address_list_append, &compose->to_list);
3140 #if 0 /* NEW COMPOSE GUI */
3141         if (compose->use_bcc) {
3142                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
3143                 if (*str != '\0') {
3144                         Xstrdup_a(str, str, return -1);
3145                         g_strstrip(str);
3146                         if (*str != '\0') {
3147                                 compose->to_list = address_list_append
3148                                         (compose->to_list, str);
3149                                 compose_convert_header(buf, sizeof(buf), str,
3150                                                        strlen("Bcc: "));
3151                                 fprintf(fp, "Bcc: %s\n", buf);
3152                         }
3153                 }
3154         }
3155 #endif
3156         if (!is_draft && !compose->to_list && !compose->newsgroup_list)
3157                 return -1;
3158
3159         /* Subject */
3160         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3161         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
3162                 Xstrdup_a(str, str, return -1);
3163                 g_strstrip(str);
3164                 if (*str != '\0') {
3165                         compose_convert_header(buf, sizeof(buf), str,
3166                                                strlen("Subject: "));
3167                         fprintf(fp, "Subject: %s\n", buf);
3168                 }
3169         }
3170
3171         /* Message-ID */
3172         if (compose->account->gen_msgid) {
3173                 compose_generate_msgid(compose, buf, sizeof(buf));
3174                 fprintf(fp, "Message-Id: <%s>\n", buf);
3175                 compose->msgid = g_strdup(buf);
3176         }
3177
3178         /* In-Reply-To */
3179         if (compose->inreplyto && compose->to_list)
3180                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
3181
3182         /* References */
3183         if (compose->references)
3184                 fprintf(fp, "References: %s\n", compose->references);
3185
3186         /* Followup-To */
3187         compose_write_headers_from_headerlist(compose, fp, "Followup-To", NULL, NULL);
3188 #if 0 /* NEW COMPOSE GUI */
3189         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
3190                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
3191                 if (*str != '\0') {
3192                         Xstrdup_a(str, str, return -1);
3193                         g_strstrip(str);
3194                         remove_space(str);
3195                         if (*str != '\0') {
3196                                 compose_convert_header(buf, sizeof(buf), str,
3197                                                        strlen("Followup-To: "));
3198                                 fprintf(fp, "Followup-To: %s\n", buf);
3199                         }
3200                 }
3201         }
3202 #endif
3203         /* Reply-To */
3204         compose_write_headers_from_headerlist(compose, fp, "Reply-To", NULL, NULL);
3205 #if 0 /* NEW COMPOSE GUI */
3206         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
3207                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
3208                 if (*str != '\0') {
3209                         Xstrdup_a(str, str, return -1);
3210                         g_strstrip(str);
3211                         if (*str != '\0') {
3212                                 compose_convert_header(buf, sizeof(buf), str,
3213                                                        strlen("Reply-To: "));
3214                                 fprintf(fp, "Reply-To: %s\n", buf);
3215                         }
3216                 }
3217         }
3218 #endif
3219         /* Organization */
3220         if (compose->account->organization &&
3221             !IS_IN_CUSTOM_HEADER("Organization")) {
3222                 compose_convert_header(buf, sizeof(buf),
3223                                        compose->account->organization,
3224                                        strlen("Organization: "));
3225                 fprintf(fp, "Organization: %s\n", buf);
3226         }
3227
3228         /* Program version and system info */
3229         /* uname(&utsbuf); */
3230         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
3231                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
3232                         prog_version,
3233                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3234                         HOST_ALIAS);
3235                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3236         }
3237         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
3238                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
3239                         prog_version,
3240                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3241                         HOST_ALIAS);
3242                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3243         }
3244
3245         /* custom headers */
3246         if (compose->account->add_customhdr) {
3247                 GSList *cur;
3248
3249                 for (cur = compose->account->customhdr_list; cur != NULL;
3250                      cur = cur->next) {
3251                         CustomHeader *chdr = (CustomHeader *)cur->data;
3252
3253                         if (strcasecmp(chdr->name, "Date")                      != 0 &&
3254                             strcasecmp(chdr->name, "From")                      != 0 &&
3255                             strcasecmp(chdr->name, "To")                        != 0 &&
3256                             strcasecmp(chdr->name, "Sender")                    != 0 &&
3257                             strcasecmp(chdr->name, "Message-Id")                != 0 &&
3258                             strcasecmp(chdr->name, "In-Reply-To")               != 0 &&
3259                             strcasecmp(chdr->name, "References")                != 0 &&
3260                             strcasecmp(chdr->name, "Mime-Version")              != 0 &&
3261                             strcasecmp(chdr->name, "Content-Type")              != 0 &&
3262                             strcasecmp(chdr->name, "Content-Transfer-Encoding") != 0)
3263                                 compose_convert_header
3264                                         (buf, sizeof(buf),
3265                                          chdr->value ? chdr->value : "",
3266                                          strlen(chdr->name) + 2);
3267                         fprintf(fp, "%s: %s\n", chdr->name, buf);
3268                 }
3269         }
3270
3271         /* MIME */
3272         fprintf(fp, "Mime-Version: 1.0\n");
3273         if (compose_use_attach(compose)) {
3274                 get_rfc822_date(buf, sizeof(buf));
3275                 subst_char(buf, ' ', '_');
3276                 subst_char(buf, ',', '_');
3277                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
3278                                                     buf, (guint)compose);
3279                 fprintf(fp,
3280                         "Content-Type: multipart/mixed;\n"
3281                         " boundary=\"%s\"\n", compose->boundary);
3282         } else {
3283                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
3284                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3285                         procmime_get_encoding_str(encoding));
3286         }
3287
3288         /* Request Return Receipt */
3289         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
3290                 if (compose->return_receipt) {
3291                         if (compose->account->name
3292                             && *compose->account->name) {
3293                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
3294                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
3295                         } else
3296                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
3297                 }
3298         }
3299
3300         /* separator between header and body */
3301         fputs("\n", fp);
3302
3303         return 0;
3304 }
3305
3306 #undef IS_IN_CUSTOM_HEADER
3307
3308 static void compose_convert_header(gchar *dest, gint len, gchar *src,
3309                                    gint header_len)
3310 {
3311         g_return_if_fail(src != NULL);
3312         g_return_if_fail(dest != NULL);
3313
3314         if (len < 1) return;
3315
3316         remove_return(src);
3317
3318         if (is_ascii_str(src)) {
3319                 strncpy2(dest, src, len);
3320                 dest[len - 1] = '\0';
3321                 return;
3322         } else
3323                 conv_encode_header(dest, len, src, header_len);
3324 }
3325
3326 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
3327 {
3328         struct tm *lt;
3329         time_t t;
3330         gchar *addr;
3331
3332         t = time(NULL);
3333         lt = localtime(&t);
3334
3335         if (compose->account && compose->account->address &&
3336             *compose->account->address) {
3337                 if (strchr(compose->account->address, '@'))
3338                         addr = g_strdup(compose->account->address);
3339                 else
3340                         addr = g_strconcat(compose->account->address, "@",
3341                                            get_domain_name(), NULL);
3342         } else
3343                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3344                                    NULL);
3345
3346         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3347                    lt->tm_year + 1900, lt->tm_mon + 1,
3348                    lt->tm_mday, lt->tm_hour,
3349                    lt->tm_min, lt->tm_sec,
3350                    (guint)random(), addr);
3351
3352         debug_print(_("generated Message-ID: %s\n"), buf);
3353
3354         g_free(addr);
3355 }
3356
3357
3358 static void compose_add_entry_field(GtkWidget *table, GtkWidget **hbox,
3359                                     GtkWidget **entry, gint *count,
3360                                     const gchar *label_str,
3361                                     gboolean is_addr_entry)
3362 {
3363         GtkWidget *label;
3364
3365         if (GTK_TABLE(table)->nrows < (*count) + 1)
3366                 gtk_table_resize(GTK_TABLE(table), (*count) + 1, 2);
3367
3368         *hbox = gtk_hbox_new(FALSE, 0);
3369         label = gtk_label_new
3370                 (prefs_common.trans_hdr ? gettext(label_str) : label_str);
3371         gtk_box_pack_end(GTK_BOX(*hbox), label, FALSE, FALSE, 0);
3372         gtk_table_attach(GTK_TABLE(table), *hbox, 0, 1, *count, (*count) + 1,
3373                          GTK_FILL, 0, 2, 0);
3374         *entry = gtk_entry_new();
3375         gtk_table_attach
3376                 (GTK_TABLE(table), *entry, 1, 2, *count, (*count) + 1, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0);
3377 #if 0 /* NEW COMPOSE GUI */
3378         if (GTK_TABLE(table)->nrows > (*count) + 1)
3379                 gtk_table_set_row_spacing(GTK_TABLE(table), *count, 4);
3380 #endif
3381
3382         if (is_addr_entry)
3383                 address_completion_register_entry(GTK_ENTRY(*entry));
3384
3385         (*count)++;
3386 }
3387
3388 static void compose_create_header_entry(Compose *compose) {
3389         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3390
3391         GtkWidget *combo;
3392         GtkWidget *entry;
3393         GList *combo_list = NULL;
3394         gchar **string, *header;
3395         compose_headerentry *headerentry = g_new0(compose_headerentry, 1);
3396
3397         /* Combo box */
3398         combo = gtk_combo_new();
3399         string = headers; 
3400         while(*string != NULL) {
3401             combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
3402             string++;
3403         }
3404         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
3405         g_list_free(combo_list);
3406         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), FALSE);
3407         gtk_widget_show(combo);
3408         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
3409         if(compose->header_last) {      
3410                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
3411         } else {
3412                 switch(compose->account->protocol) {
3413                         case A_NNTP:
3414                                 header = _("Newsgroups:");
3415                                 break;
3416                         default:
3417                                 header = _("To:");
3418                                 break;
3419                 }                                                                   
3420         }
3421         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
3422
3423         /* Entry field */
3424         entry = gtk_entry_new(); 
3425         gtk_widget_show(entry);
3426         gtk_table_attach(GTK_TABLE(compose->header_table), entry, 1, 2, compose->header_nextrow, compose->header_nextrow+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
3427
3428         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
3429         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
3430
3431         address_completion_register_entry(GTK_ENTRY(entry));
3432
3433         headerentry->compose = compose;
3434         headerentry->combo = combo;
3435         headerentry->entry = entry;
3436         headerentry->headernum = compose->header_nextrow;
3437
3438         compose->header_nextrow++;
3439         compose->header_last = headerentry;
3440 }
3441
3442 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) {
3443         compose_headerentry *last_header;
3444         
3445         last_header = compose->header_last;
3446         
3447         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
3448         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
3449 }
3450
3451 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
3452 {
3453         Compose   *compose;
3454         GtkWidget *window;
3455         GtkWidget *vbox;
3456         GtkWidget *menubar;
3457         GtkWidget *handlebox;
3458
3459         GtkWidget *notebook;
3460
3461         GtkWidget *vbox2;
3462
3463         GtkWidget *table_vbox;
3464         GtkWidget *label;
3465         GtkWidget *from_optmenu_hbox;
3466 #if 0 /* NEW COMPOSE GUI */
3467         GtkWidget *to_entry;
3468         GtkWidget *to_hbox;
3469         GtkWidget *newsgroups_entry;
3470         GtkWidget *newsgroups_hbox;
3471 #endif
3472         GtkWidget *header_scrolledwin;
3473         GtkWidget *header_table;
3474         GtkWidget *subject_entry;
3475 #if 0 /* NEW COMPOSE GUI */
3476         GtkWidget *cc_entry;
3477         GtkWidget *cc_hbox;
3478         GtkWidget *bcc_entry;
3479         GtkWidget *bcc_hbox;
3480         GtkWidget *reply_entry;
3481         GtkWidget *reply_hbox;
3482         GtkWidget *followup_entry;
3483         GtkWidget *followup_hbox;
3484 #endif
3485         GtkWidget *paned;
3486
3487         GtkWidget *attach_scrwin;
3488         GtkWidget *attach_clist;
3489
3490         GtkWidget *edit_vbox;
3491         GtkWidget *ruler_hbox;
3492         GtkWidget *ruler;
3493         GtkWidget *scrolledwin;
3494         GtkWidget *text;
3495
3496         GtkWidget *table;
3497         GtkWidget *hbox;
3498
3499         gchar *titles[] = {_("MIME type"), _("Size"), _("Name")};
3500         guint n_menu_entries;
3501         GtkStyle  *style, *new_style;
3502         GdkColormap *cmap;
3503         GdkColor color[1];
3504         gboolean success[1];
3505         GdkFont   *font;
3506         GtkWidget *popupmenu;
3507         GtkWidget *menuitem;
3508         GtkItemFactory *popupfactory;
3509         GtkItemFactory *ifactory;
3510         GtkWidget *tmpl_menu;
3511         gint n_entries;
3512         gint count = 0;
3513         gint i;
3514
3515 #if USE_PSPELL
3516         GtkPspell * gtkpspell = NULL;
3517 #endif
3518
3519         g_return_val_if_fail(account != NULL, NULL);
3520
3521         debug_print(_("Creating compose window...\n"));
3522         compose = g_new0(Compose, 1);
3523
3524         compose->account = account;
3525         compose->orig_account = account;
3526
3527         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3528         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
3529         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
3530         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
3531                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
3532         gtk_signal_connect(GTK_OBJECT(window), "destroy",
3533                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
3534         gtk_signal_connect(GTK_OBJECT(window), "focus_in_event",
3535                            GTK_SIGNAL_FUNC(manage_window_focus_in), NULL);
3536         gtk_signal_connect(GTK_OBJECT(window), "focus_out_event",
3537                            GTK_SIGNAL_FUNC(manage_window_focus_out), NULL);
3538         gtk_widget_realize(window);
3539
3540         gtkut_widget_set_composer_icon(window);
3541
3542         vbox = gtk_vbox_new(FALSE, 0);
3543         gtk_container_add(GTK_CONTAINER(window), vbox);
3544
3545         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
3546         menubar = menubar_create(window, compose_entries,
3547                                  n_menu_entries, "<Compose>", compose);
3548         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
3549
3550         handlebox = gtk_handle_box_new();
3551         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
3552
3553         compose_toolbar_create(compose, handlebox);
3554
3555         vbox2 = gtk_vbox_new(FALSE, 2);
3556         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
3557         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
3558
3559         table_vbox = gtk_vbox_new(FALSE, 0);
3560         gtk_box_pack_start(GTK_BOX(vbox2), table_vbox, FALSE, TRUE, 0);
3561         gtk_container_set_border_width(GTK_CONTAINER(table_vbox),
3562                                        BORDER_WIDTH * 2);
3563
3564         /* Notebook */
3565         notebook = gtk_notebook_new();
3566         gtk_widget_set_usize(notebook, -1, 180);
3567         gtk_widget_show(notebook);
3568
3569         /* header labels and entries */
3570         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
3571         gtk_widget_show(header_scrolledwin);
3572         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
3573         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), header_scrolledwin, gtk_label_new(_("Header")));
3574
3575         header_table = gtk_table_new(2, 2, FALSE);
3576         gtk_widget_show(header_table);
3577         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
3578         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
3579         count = 0;
3580
3581         /* option menu for selecting accounts */
3582         hbox = gtk_hbox_new(FALSE, 0);
3583         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
3584         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
3585         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
3586                          GTK_FILL, 0, 2, 0);
3587         from_optmenu_hbox = compose_account_option_menu_create(compose);
3588         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
3589                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
3590 #if 0 /* NEW COMPOSE GUI */
3591         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
3592 #endif
3593         count++;
3594
3595         /* Subject */
3596         compose_add_entry_field(header_table, &hbox, &subject_entry, &count,
3597                                 "Subject:", FALSE);
3598
3599         compose->header_table = header_table;
3600         compose->header_list = NULL;
3601         compose->header_nextrow = count;
3602
3603         compose_create_header_entry(compose);
3604
3605 #if 0 /* NEW COMPOSE GUI */
3606         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
3607                                 "To:", TRUE); 
3608         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
3609         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
3610                                 &count, "Newsgroups:", FALSE);
3611         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
3612
3613         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
3614
3615         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
3616                                 "Cc:", TRUE);
3617         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
3618         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
3619                                 "Bcc:", TRUE);
3620         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
3621         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
3622                                 "Reply-To:", TRUE);
3623         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
3624         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
3625                                 "Followup-To:", FALSE);
3626         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
3627
3628         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
3629
3630         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
3631                            GTK_SIGNAL_FUNC(to_activated), compose);
3632         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
3633                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
3634         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
3635                            GTK_SIGNAL_FUNC(subject_activated), compose);
3636         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
3637                            GTK_SIGNAL_FUNC(cc_activated), compose);
3638         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
3639                            GTK_SIGNAL_FUNC(bcc_activated), compose);
3640         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
3641                            GTK_SIGNAL_FUNC(replyto_activated), compose);
3642         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
3643                            GTK_SIGNAL_FUNC(followupto_activated), compose);
3644
3645         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
3646                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3647         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
3648                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3649         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
3650                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3651         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
3652                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3653         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
3654                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3655         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
3656                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3657         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
3658                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3659 #endif
3660
3661         /* attachment list */
3662         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
3663         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), attach_scrwin, gtk_label_new(_("Attachments")));
3664         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
3665                                        GTK_POLICY_AUTOMATIC,
3666                                        GTK_POLICY_ALWAYS);
3667         gtk_widget_set_usize(attach_scrwin, -1, 80);
3668
3669         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
3670         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
3671                                            GTK_JUSTIFY_RIGHT);
3672         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
3673         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
3674         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
3675                                      GTK_SELECTION_EXTENDED);
3676         for (i = 0; i < N_ATTACH_COLS; i++)
3677                 GTK_WIDGET_UNSET_FLAGS
3678                         (GTK_CLIST(attach_clist)->column[i].button,
3679                          GTK_CAN_FOCUS);
3680         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
3681
3682         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
3683                            GTK_SIGNAL_FUNC(attach_selected), compose);
3684         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
3685                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
3686         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
3687                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
3688
3689         /* drag and drop */
3690         gtk_drag_dest_set(attach_clist,
3691                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
3692                           GDK_ACTION_COPY);
3693         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
3694                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
3695                            compose);
3696
3697
3698         edit_vbox = gtk_vbox_new(FALSE, 0);
3699 #if 0 /* NEW COMPOSE GUI */
3700         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
3701 #endif
3702
3703         /* ruler */
3704         ruler_hbox = gtk_hbox_new(FALSE, 0);
3705         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
3706
3707         ruler = gtk_shruler_new();
3708         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
3709         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
3710                            BORDER_WIDTH + 1);
3711         gtk_widget_set_usize(ruler_hbox, 1, -1);
3712
3713         /* text widget */
3714         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
3715         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
3716                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
3717         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
3718         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
3719
3720         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
3721                             (GTK_SCROLLED_WINDOW(scrolledwin)),
3722                             gtk_scrolled_window_get_vadjustment
3723                             (GTK_SCROLLED_WINDOW(scrolledwin)));
3724         GTK_STEXT(text)->default_tab_width = 8;
3725         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
3726
3727         if (prefs_common.block_cursor) {
3728                 GTK_STEXT(text)->cursor_type = STEXT_CURSOR_BLOCK;
3729         }
3730         
3731         if (prefs_common.smart_wrapping) {      
3732                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
3733                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
3734         }               
3735
3736         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
3737
3738         gtk_signal_connect(GTK_OBJECT(text), "changed",
3739                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
3740         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
3741                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3742         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
3743                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
3744                                  compose);
3745 #if 0
3746         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
3747                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
3748                                  compose);
3749 #endif
3750         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
3751                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
3752                                  ruler);
3753
3754         /* drag and drop */
3755         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
3756                           GDK_ACTION_COPY);
3757         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
3758                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
3759                            compose);
3760 #if USE_PSPELL
3761         if (prefs_common.enable_pspell) {
3762                 gtkpspell = gtkpspell_new_with_config(gtkpspellconfig,
3763                                                       prefs_common.pspell_path,
3764                                                       prefs_common.dictionary,
3765                                                       PSPELL_FASTMODE,
3766                                                       conv_get_current_charset_str());
3767                 if (gtkpspell == NULL)
3768                         prefs_common.enable_pspell = FALSE;
3769                 else
3770                         gtkpspell_attach(gtkpspell, GTK_STEXT(text));
3771         }
3772 #endif
3773         gtk_widget_show_all(vbox);
3774
3775         /* pane between attach clist and text */
3776         paned = gtk_vpaned_new();
3777         gtk_container_add(GTK_CONTAINER(vbox2), paned);
3778         gtk_paned_add1(GTK_PANED(paned), notebook);
3779         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
3780         gtk_widget_show_all(paned);
3781
3782         style = gtk_widget_get_style(text);
3783
3784         /* workaround for the slow down of GtkText when using Pixmap theme */
3785         if (style->engine) {
3786                 GtkThemeEngine *engine;
3787
3788                 engine = style->engine;
3789                 style->engine = NULL;
3790                 new_style = gtk_style_copy(style);
3791                 style->engine = engine;
3792         } else
3793                 new_style = gtk_style_copy(style);</