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