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