* src/compose.c
[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 = NULL;
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 queueheader_buf[BUFFSIZE];
1217                 gint id;
1218
1219                 /* Select Account from queue headers */
1220                 if (!get_header_from_msginfo(msginfo, queueheader_buf, 
1221                                              sizeof(queueheader_buf), "NAID:")) {
1222                         id = atoi(&queueheader_buf[5]);
1223                         account = account_find_from_id(id);
1224                 }
1225                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1226                                                     sizeof(queueheader_buf), "MAID:")) {
1227                         id = atoi(&queueheader_buf[5]);
1228                         account = account_find_from_id(id);
1229                 }
1230                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1231                                                                 sizeof(queueheader_buf), "S:")) {
1232                         account = account_find_from_address(queueheader_buf);
1233                 }
1234         } else 
1235                 account = msginfo->folder->folder->account;
1236
1237         if (!account && prefs_common.reedit_account_autosel) {
1238                 gchar from[BUFFSIZE];
1239                 if (!get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1240                         extract_address(from);
1241                         account = account_find_from_address(from);
1242                 }
1243         }
1244         if (!account) account = cur_account;
1245         g_return_if_fail(account != NULL);
1246
1247         compose = compose_create(account, COMPOSE_REEDIT);
1248         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1249
1250         if (msginfo->folder->stype == F_QUEUE) {
1251                 gchar queueheader_buf[BUFFSIZE];
1252
1253                 /* Set message save folder */
1254                 if (!get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1255                         gint startpos = 0;
1256
1257                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1258                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1259                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1260                 }
1261         }
1262         
1263         if (compose_parse_header(compose, msginfo) < 0) return;
1264         compose_reedit_set_entry(compose, msginfo);
1265
1266         text = GTK_STEXT(compose->text);
1267         gtk_stext_freeze(text);
1268
1269         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1270                 g_warning(_("Can't get text part\n"));
1271         else {
1272                 while (fgets(buf, sizeof(buf), fp) != NULL)
1273                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1274                 fclose(fp);
1275         }
1276         compose_attach_parts(compose, msginfo);
1277
1278         gtk_stext_thaw(text);
1279         gtk_widget_grab_focus(compose->text);
1280
1281         if (prefs_common.auto_exteditor)
1282                 compose_exec_ext_editor(compose);
1283 }
1284
1285 GList *compose_get_compose_list(void)
1286 {
1287         return compose_list;
1288 }
1289
1290 void compose_entry_append(Compose *compose, const gchar *address,
1291                           ComposeEntryType type)
1292 {
1293         GtkEntry *entry;
1294         const gchar *text;
1295         gchar *header;
1296
1297         if (!address || *address == '\0') return;
1298
1299 #if 0 /* NEW COMPOSE GUI */
1300         switch (type) {
1301         case COMPOSE_CC:
1302                 entry = GTK_ENTRY(compose->cc_entry);
1303                 break;
1304         case COMPOSE_BCC:
1305                 entry = GTK_ENTRY(compose->bcc_entry);
1306                 break;
1307         case COMPOSE_NEWSGROUPS:
1308                 entry = GTK_ENTRY(compose->newsgroups_entry);
1309                 break;
1310         case COMPOSE_TO:
1311         default:
1312                 entry = GTK_ENTRY(compose->to_entry);
1313                 break;
1314         }
1315
1316         text = gtk_entry_get_text(entry);
1317         if (*text != '\0')
1318                 gtk_entry_append_text(entry, ", ");
1319         gtk_entry_append_text(entry, address);
1320 #endif
1321
1322         switch (type) {
1323         case COMPOSE_CC:
1324                 header = N_("Cc:");
1325                 break;
1326         case COMPOSE_BCC:
1327                 header = N_("Bcc:");
1328                 break;
1329         case COMPOSE_REPLYTO:
1330                 header = N_("Reply-To:");
1331                 break;
1332         case COMPOSE_NEWSGROUPS:
1333                 header = N_("Newsgroups:");
1334                 break;
1335         case COMPOSE_FOLLOWUPTO:
1336                 header = N_( "Followup-To:");
1337                 break;
1338         case COMPOSE_TO:
1339         default:
1340                 header = N_("To:");
1341                 break;
1342         }
1343         header = prefs_common.trans_hdr ? gettext(header) : header;
1344
1345         compose_add_header_entry(compose, header, (gchar *)address);
1346 }
1347
1348 static void compose_entries_set(Compose *compose, const gchar *mailto)
1349 {
1350         gchar *subject = NULL;
1351         gchar *to = NULL;
1352         gchar *cc = NULL;
1353         gchar *bcc = NULL;
1354         gchar *body = NULL;
1355         gchar *p;
1356         gchar *tmp_mailto;
1357
1358         Xstrdup_a(tmp_mailto, mailto, return);
1359
1360         to = tmp_mailto;
1361
1362         p = strchr(tmp_mailto, '?');
1363         if (p) {
1364                 *p = '\0';
1365                 p++;
1366         }
1367
1368         while (p) {
1369                 gchar *field, *value;
1370
1371                 field = p;
1372
1373                 p = strchr(p, '=');
1374                 if (!p) break;
1375                 *p = '\0';
1376                 p++;
1377
1378                 value = p;
1379
1380                 p = strchr(p, '&');
1381                 if (p) {
1382                         *p = '\0';
1383                         p++;
1384                 }
1385
1386                 if (*value == '\0') continue;
1387
1388                 if (!g_strcasecmp(field, "subject")) {
1389                         Xalloca(subject, strlen(value) + 1, return);
1390                         decode_uri(subject, value);
1391                 } else if (!g_strcasecmp(field, "cc")) {
1392                         cc = value;
1393                 } else if (!g_strcasecmp(field, "bcc")) {
1394                         bcc = value;
1395                 } else if (!g_strcasecmp(field, "body")) {
1396                         Xalloca(body, strlen(value) + 1, return);
1397                         decode_uri(body, value);
1398                 }
1399         }
1400
1401         if (to)
1402                 compose_entry_append(compose, to, COMPOSE_TO);
1403         if (subject)
1404                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1405         if (cc)
1406                 compose_entry_append(compose, cc, COMPOSE_CC);
1407         if (bcc)
1408                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1409         if (body) {
1410                 gtk_stext_insert(GTK_STEXT(compose->text),
1411                                 NULL, NULL, NULL, body, -1);
1412                 gtk_stext_insert(GTK_STEXT(compose->text),
1413                                 NULL, NULL, NULL, "\n", 1);
1414         }
1415 }
1416
1417 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1418 {
1419         static HeaderEntry hentry[] = {{"Reply-To:",       NULL, TRUE},
1420                                        {"Cc:",             NULL, FALSE},
1421                                        {"References:",     NULL, FALSE},
1422                                        {"Bcc:",            NULL, FALSE},
1423                                        {"Newsgroups:",     NULL, FALSE},
1424                                        {"Followup-To:",    NULL, FALSE},
1425                                        {"X-Mailing-List:", NULL, FALSE},
1426                                        {"X-BeenThere:",    NULL, FALSE},
1427                                        {NULL,              NULL, FALSE}};
1428
1429         enum
1430         {
1431                 H_REPLY_TO       = 0,
1432                 H_CC             = 1,
1433                 H_REFERENCES     = 2,
1434                 H_BCC            = 3,
1435                 H_NEWSGROUPS     = 4,
1436                 H_FOLLOWUP_TO    = 5,
1437                 H_X_MAILING_LIST = 6,
1438                 H_X_BEENTHERE    = 7
1439         };
1440
1441         FILE *fp;
1442
1443         g_return_val_if_fail(msginfo != NULL, -1);
1444
1445         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1446         procheader_get_header_fields(fp, hentry);
1447         fclose(fp);
1448
1449         if (hentry[H_REPLY_TO].body != NULL) {
1450                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1451                 compose->replyto = hentry[H_REPLY_TO].body;
1452                 hentry[H_REPLY_TO].body = NULL;
1453         }
1454         if (hentry[H_CC].body != NULL) {
1455                 conv_unmime_header_overwrite(hentry[H_CC].body);
1456                 compose->cc = hentry[H_CC].body;
1457                 hentry[H_CC].body = NULL;
1458         }
1459         if (hentry[H_X_MAILING_LIST].body != NULL) {
1460                 /* this is good enough to parse debian-devel */
1461                 gchar *buf = g_malloc(strlen(hentry[H_X_MAILING_LIST].body) + 1);
1462                 g_return_val_if_fail(buf != NULL, -1 );
1463                 if (1 == sscanf(hentry[H_X_MAILING_LIST].body, "<%[^>]>", buf))
1464                         compose->mailinglist = g_strdup(buf);
1465                 g_free(buf);
1466                 g_free(hentry[H_X_MAILING_LIST].body);
1467                 hentry[H_X_MAILING_LIST].body = NULL ;
1468         }
1469         if (hentry[H_X_BEENTHERE].body != NULL) {
1470                 /* this is good enough to parse the sylpheed-claws lists */
1471                 gchar *buf = g_malloc(strlen(hentry[H_X_BEENTHERE].body) + 1);
1472                 g_return_val_if_fail(buf != NULL, -1 );
1473                 if (1 == sscanf(hentry[H_X_BEENTHERE].body, "%[^>]", buf))
1474                         compose->mailinglist = g_strdup(buf);
1475                 g_free(buf);
1476                 g_free(hentry[H_X_BEENTHERE].body);
1477                 hentry[H_X_BEENTHERE].body = NULL ;
1478         }
1479         if (hentry[H_REFERENCES].body != NULL) {
1480                 if (compose->mode == COMPOSE_REEDIT)
1481                         compose->references = hentry[H_REFERENCES].body;
1482                 else {
1483                         compose->references = compose_parse_references
1484                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1485                         g_free(hentry[H_REFERENCES].body);
1486                 }
1487                 hentry[H_REFERENCES].body = NULL;
1488         }
1489         if (hentry[H_BCC].body != NULL) {
1490                 if (compose->mode == COMPOSE_REEDIT) {
1491                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1492                         compose->bcc = hentry[H_BCC].body;
1493                 } else
1494                         g_free(hentry[H_BCC].body);
1495                 hentry[H_BCC].body = NULL;
1496         }
1497         if (hentry[H_NEWSGROUPS].body != NULL) {
1498                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1499                 hentry[H_NEWSGROUPS].body = NULL;
1500         }
1501         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1502                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1503                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1504                 hentry[H_FOLLOWUP_TO].body = NULL;
1505         }
1506
1507         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1508                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1509         else if (compose->mode != COMPOSE_REEDIT &&
1510                  msginfo->msgid && *msginfo->msgid) {
1511                 compose->inreplyto = g_strdup(msginfo->msgid);
1512
1513                 if (!compose->references) {
1514                         if (msginfo->inreplyto && *msginfo->inreplyto)
1515                                 compose->references =
1516                                         g_strdup_printf("<%s>\n\t<%s>",
1517                                                         msginfo->inreplyto,
1518                                                         msginfo->msgid);
1519                         else
1520                                 compose->references =
1521                                         g_strconcat("<", msginfo->msgid, ">",
1522                                                     NULL);
1523                 }
1524         }
1525
1526         return 0;
1527 }
1528
1529 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1530 {
1531         GSList *ref_id_list, *cur;
1532         GString *new_ref;
1533         gchar *new_ref_str;
1534
1535         ref_id_list = references_list_append(NULL, ref);
1536         if (!ref_id_list) return NULL;
1537         if (msgid && *msgid)
1538                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1539
1540         for (;;) {
1541                 gint len = 0;
1542
1543                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1544                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1545                         len += strlen((gchar *)cur->data) + 5;
1546
1547                 if (len > MAX_REFERENCES_LEN) {
1548                         /* remove second message-ID */
1549                         if (ref_id_list && ref_id_list->next &&
1550                             ref_id_list->next->next) {
1551                                 g_free(ref_id_list->next->data);
1552                                 ref_id_list = g_slist_remove
1553                                         (ref_id_list, ref_id_list->next->data);
1554                         } else {
1555                                 slist_free_strings(ref_id_list);
1556                                 g_slist_free(ref_id_list);
1557                                 return NULL;
1558                         }
1559                 } else
1560                         break;
1561         }
1562
1563         new_ref = g_string_new("");
1564         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1565                 if (new_ref->len > 0)
1566                         g_string_append(new_ref, "\n\t");
1567                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1568         }
1569
1570         slist_free_strings(ref_id_list);
1571         g_slist_free(ref_id_list);
1572
1573         new_ref_str = new_ref->str;
1574         g_string_free(new_ref, FALSE);
1575
1576         return new_ref_str;
1577 }
1578
1579 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1580                                 const gchar *fmt, const gchar *qmark)
1581 {
1582         GtkSText *text = GTK_STEXT(compose->text);
1583         gchar *quote_str = NULL;
1584         gchar *buf;
1585         gchar *p, *lastp;
1586         gint len;
1587
1588         if (qmark != NULL) {
1589                 quote_fmt_init(msginfo, NULL);
1590                 quote_fmt_scan_string(qmark);
1591                 quote_fmt_parse();
1592
1593                 buf = quote_fmt_get_buffer();
1594                 if (buf == NULL)
1595                         alertpanel_error(_("Quote mark format error."));
1596                 else
1597                         Xstrdup_a(quote_str, buf, return NULL)
1598         }
1599
1600         if (fmt && *fmt != '\0') {
1601                 quote_fmt_init(msginfo, quote_str);
1602                 quote_fmt_scan_string(fmt);
1603                 quote_fmt_parse();
1604
1605                 buf = quote_fmt_get_buffer();
1606                 if (buf == NULL) {
1607                         alertpanel_error(_("Message reply/forward format error."));
1608                         return NULL;
1609                 }
1610         } else
1611                 buf = "";
1612
1613         gtk_stext_freeze(text);
1614         gtk_stext_set_point(text, 0);
1615         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
1616
1617         for (p = buf; *p != '\0'; ) {
1618                 lastp = strchr(p, '\n');
1619                 len = lastp ? lastp - p + 1 : -1;
1620                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1621                 if (lastp)
1622                         p = lastp + 1;
1623                 else
1624                         break;
1625         }
1626
1627         gtk_stext_thaw(text);
1628
1629         return buf;
1630 }
1631
1632 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1633                                     gboolean to_all, gboolean ignore_replyto,
1634                                     gboolean followup_and_reply_to)
1635 {
1636         GSList *cc_list;
1637         GSList *cur;
1638         gchar *from;
1639         GHashTable *to_table;
1640
1641         g_return_if_fail(compose->account != NULL);
1642         g_return_if_fail(msginfo != NULL);
1643
1644         if ((compose->account->protocol != A_NNTP) || followup_and_reply_to)
1645                 compose_entry_append(compose,
1646                                     ((compose->replyto && !ignore_replyto)
1647                                      ? compose->replyto
1648                                      : (compose->mailinglist && !ignore_replyto)
1649                                      ? compose->mailinglist
1650                                      : msginfo->from ? msginfo->from : ""),
1651                                      COMPOSE_TO);
1652         if (compose->account->protocol == A_NNTP) {
1653                 if (ignore_replyto)
1654                         compose_entry_append
1655                                 (compose, msginfo->from ? msginfo->from : "",
1656                                  COMPOSE_TO);
1657                 else
1658                         compose_entry_append
1659                                 (compose,
1660                                  compose->followup_to ? compose->followup_to
1661                                  : compose->newsgroups ? compose->newsgroups
1662                                  : "",
1663                                  COMPOSE_NEWSGROUPS);
1664         }
1665
1666         if (msginfo->subject && *msginfo->subject) {
1667                 gchar *buf, *buf2, *p;
1668
1669                 buf = g_strdup(msginfo->subject);
1670                 while (!strncasecmp(buf, "Re:", 3)) {
1671                         p = buf + 3;
1672                         while (isspace(*p)) p++;
1673                         memmove(buf, p, strlen(p) + 1);
1674                 }
1675
1676                 buf2 = g_strdup_printf("Re: %s", buf);
1677                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1678                 g_free(buf2);
1679                 g_free(buf);
1680         } else
1681                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1682
1683         if (!to_all || compose->account->protocol == A_NNTP) return;
1684
1685         from = g_strdup(compose->replyto ? compose->replyto :
1686                         msginfo->from ? msginfo->from : "");
1687         extract_address(from);
1688
1689         cc_list = address_list_append(NULL, msginfo->to);
1690         cc_list = address_list_append(cc_list, compose->cc);
1691
1692         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1693         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1694         if (compose->account)
1695                 g_hash_table_insert(to_table, compose->account->address,
1696                                     GINT_TO_POINTER(1));
1697
1698         /* remove address on To: and that of current account */
1699         for (cur = cc_list; cur != NULL; ) {
1700                 GSList *next = cur->next;
1701
1702                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1703                         cc_list = g_slist_remove(cc_list, cur->data);
1704                 else
1705                         g_hash_table_insert(to_table, cur->data, cur);
1706
1707                 cur = next;
1708         }
1709         g_hash_table_destroy(to_table);
1710         g_free(from);
1711
1712         if (cc_list) {
1713                 for (cur = cc_list; cur != NULL; cur = cur->next)
1714                         compose_entry_append(compose, (gchar *)cur->data,
1715                                              COMPOSE_CC);
1716                 slist_free_strings(cc_list);
1717                 g_slist_free(cc_list);
1718         }
1719 }
1720
1721 #define SET_ENTRY(entry, str) \
1722 { \
1723         if (str && *str) \
1724                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1725 }
1726
1727 #define SET_ADDRESS(type, str) \
1728 { \
1729         if (str && *str) \
1730                 compose_entry_append(compose, str, type); \
1731 }
1732
1733 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1734 {
1735         g_return_if_fail(msginfo != NULL);
1736
1737         SET_ENTRY(subject_entry, msginfo->subject);
1738         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1739         SET_ADDRESS(COMPOSE_CC, compose->cc);
1740         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1741         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1742
1743         compose_show_first_last_header(compose, TRUE);
1744
1745 #if 0 /* NEW COMPOSE GUI */
1746         if (compose->bcc) {
1747                 GtkItemFactory *ifactory;
1748                 GtkWidget *menuitem;
1749
1750                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1751                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Bcc");
1752                 gtk_check_menu_item_set_active
1753                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1754         }
1755         if (compose->replyto) {
1756                 GtkItemFactory *ifactory;
1757                 GtkWidget *menuitem;
1758
1759                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1760                 menuitem = gtk_item_factory_get_item
1761                         (ifactory, "/View/Reply to");
1762                 gtk_check_menu_item_set_active
1763                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1764         }
1765 #endif
1766 }
1767
1768 #undef SET_ENTRY
1769 #undef SET_ADDRESS
1770
1771 static void compose_exec_sig(Compose *compose, gchar *sigfile)
1772 {
1773         FILE *tmpfp;
1774         pid_t thepid;
1775         gchar *sigtext;
1776         FILE  *sigprg;
1777         gchar  *buf;
1778         size_t buf_len = 128;
1779  
1780         if (strlen(sigfile) < 2)
1781           return;
1782  
1783         sigprg = popen(sigfile+1, "r");
1784         if (sigprg) {
1785
1786                 buf = g_malloc(buf_len);
1787
1788                 if (!buf) {
1789                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1790                         "Unable to insert signature (malloc failed)\n", -1);
1791
1792                         pclose(sigprg);
1793                         return;
1794                 }
1795
1796                 while (!feof(sigprg)) {
1797                         bzero(buf, buf_len);
1798                         fread(buf, buf_len-1, 1, sigprg);
1799                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, buf, -1);
1800                 }
1801
1802                 g_free(buf);
1803                 pclose(sigprg);
1804         }
1805         else
1806         {
1807                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1808                 "Can't exec file: ", -1);
1809                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1810                 sigfile+1, -1);
1811         }
1812 }
1813
1814 static void compose_insert_sig(Compose *compose)
1815 {
1816         gchar *sigfile;
1817
1818         if (compose->account && compose->account->sig_path)
1819                 sigfile = g_strdup(compose->account->sig_path);
1820         else {
1821                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1822                                       DEFAULT_SIGNATURE, NULL);
1823         }
1824
1825         if (!is_file_or_fifo_exist(sigfile) & (sigfile[0] != '|')) {
1826                 g_free(sigfile);
1827                 return;
1828         }
1829
1830         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1831         if (prefs_common.sig_sep) {
1832                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1833                                 prefs_common.sig_sep, -1);
1834                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1835                                 "\n", 1);
1836         }
1837
1838         if (sigfile[0] == '|')
1839         {
1840                 compose_exec_sig(compose, sigfile);
1841         }
1842         else
1843         {
1844                 compose_insert_file(compose, sigfile);
1845         }
1846         g_free(sigfile);
1847 }
1848
1849 static void compose_insert_file(Compose *compose, const gchar *file)
1850 {
1851         GtkSText *text = GTK_STEXT(compose->text);
1852         gchar buf[BUFFSIZE];
1853         gint len;
1854         FILE *fp;
1855
1856         g_return_if_fail(file != NULL);
1857
1858         if ((fp = fopen(file, "r")) == NULL) {
1859                 FILE_OP_ERROR(file, "fopen");
1860                 return;
1861         }
1862
1863         gtk_stext_freeze(text);
1864
1865         while (fgets(buf, sizeof(buf), fp) != NULL) {
1866                 /* strip <CR> if DOS/Windows file,
1867                    replace <CR> with <LF> if Macintosh file. */
1868                 strcrchomp(buf);
1869                 len = strlen(buf);
1870                 if (len > 0 && buf[len - 1] != '\n') {
1871                         while (--len >= 0)
1872                                 if (buf[len] == '\r') buf[len] = '\n';
1873                 }
1874                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1875         }
1876
1877         gtk_stext_thaw(text);
1878
1879         fclose(fp);
1880 }
1881
1882 static void compose_attach_info(Compose * compose, AttachInfo * ainfo,
1883                                 ContentType cnttype)
1884 {
1885         gchar *text[N_ATTACH_COLS];
1886         gint row;
1887
1888         text[COL_MIMETYPE] = ainfo->content_type;
1889         text[COL_SIZE] = to_human_readable(ainfo->size);
1890         text[COL_NAME] = ainfo->name;
1891
1892         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1893         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1894
1895         if (cnttype != MIME_MESSAGE_RFC822)
1896                 compose_changed_cb(NULL, compose);
1897 }
1898
1899 static void compose_attach_append_with_type(Compose *compose,
1900                                             const gchar *file,
1901                                             const gchar *type,
1902                                             ContentType cnttype)
1903 {
1904         AttachInfo *ainfo;
1905         off_t size;
1906
1907         if (!is_file_exist(file)) {
1908                 g_warning(_("File %s doesn't exist\n"), file);
1909                 return;
1910         }
1911         if ((size = get_file_size(file)) < 0) {
1912                 g_warning(_("Can't get file size of %s\n"), file);
1913                 return;
1914         }
1915         if (size == 0) {
1916                 alertpanel_notice(_("File %s is empty\n"), file);
1917                 return;
1918         }
1919 #if 0 /* NEW COMPOSE GUI */
1920         if (!compose->use_attach) {
1921                 GtkItemFactory *ifactory;
1922                 GtkWidget *menuitem;
1923
1924                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1925                 menuitem = gtk_item_factory_get_item(ifactory,
1926                                                      "/Message/Attach");
1927                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1928                                                TRUE);
1929         }
1930 #endif
1931         ainfo = g_new0(AttachInfo, 1);
1932         ainfo->file = g_strdup(file);
1933
1934         if (cnttype == MIME_MESSAGE_RFC822) {
1935                 ainfo->encoding = ENC_7BIT;
1936                 ainfo->name = g_strdup_printf(_("Message: %s"),
1937                                               g_basename(file));
1938         } else {
1939                 ainfo->encoding = ENC_BASE64;
1940                 ainfo->name = g_strdup(g_basename(file));
1941         }
1942
1943         ainfo->content_type = g_strdup(type);
1944         ainfo->size = size;
1945
1946         compose_attach_info(compose, ainfo, cnttype);
1947 }
1948
1949 static void compose_attach_append(Compose *compose, const gchar *file,
1950                                   ContentType cnttype)
1951 {
1952         AttachInfo *ainfo;
1953         gchar *text[N_ATTACH_COLS];
1954         off_t size;
1955         gint row;
1956
1957         if (!is_file_exist(file)) {
1958                 g_warning(_("File %s doesn't exist\n"), file);
1959                 return;
1960         }
1961         if ((size = get_file_size(file)) < 0) {
1962                 g_warning(_("Can't get file size of %s\n"), file);
1963                 return;
1964         }
1965         if (size == 0) {
1966                 alertpanel_notice(_("File %s is empty\n"), file);
1967                 return;
1968         }
1969 #if 0 /* NEW COMPOSE GUI */
1970         if (!compose->use_attach) {
1971                 GtkItemFactory *ifactory;
1972                 GtkWidget *menuitem;
1973
1974                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1975                 menuitem = gtk_item_factory_get_item(ifactory,
1976                                                      "/View/Attachment");
1977                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1978                                                TRUE);
1979         }
1980 #endif
1981         ainfo = g_new0(AttachInfo, 1);
1982         ainfo->file = g_strdup(file);
1983
1984         if (cnttype == MIME_MESSAGE_RFC822) {
1985                 ainfo->content_type = g_strdup("message/rfc822");
1986                 ainfo->encoding = ENC_7BIT;
1987                 ainfo->name = g_strdup_printf(_("Message: %s"),
1988                                               g_basename(file));
1989         } else {
1990                 ainfo->content_type = procmime_get_mime_type(file);
1991                 if (!ainfo->content_type)
1992                         ainfo->content_type =
1993                                 g_strdup("application/octet-stream");
1994                 ainfo->encoding = ENC_BASE64;
1995                 ainfo->name = g_strdup(g_basename(file));
1996         }
1997         ainfo->size = size;
1998
1999         compose_attach_info(compose, ainfo, cnttype);
2000 }
2001
2002 #define GET_CHAR(pos, buf, len)                                              \
2003 {                                                                            \
2004         if (text->use_wchar)                                                 \
2005                 len = wctomb(buf, (wchar_t)GTK_STEXT_INDEX(text, (pos)));    \
2006         else {                                                               \
2007                 buf[0] = GTK_STEXT_INDEX(text, (pos));                       \
2008                 len = 1;                                                     \
2009         }                                                                    \
2010 }
2011
2012 static void compose_wrap_line(Compose *compose)
2013 {
2014         GtkSText *text = GTK_STEXT(compose->text);
2015         gint ch_len, last_ch_len;
2016         gchar cbuf[MB_LEN_MAX], last_ch;
2017         guint text_len;
2018         guint line_end;
2019         guint quoted;
2020         gint p_start, p_end;
2021         gint line_pos, cur_pos;
2022         gint line_len, cur_len;
2023
2024         gtk_stext_freeze(text);
2025
2026         text_len = gtk_stext_get_length(text);
2027
2028         /* check to see if the point is on the paragraph mark (empty line). */
2029         cur_pos = gtk_stext_get_point(text);
2030         GET_CHAR(cur_pos, cbuf, ch_len);
2031         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
2032                 if (cur_pos == 0)
2033                         goto compose_end; /* on the paragraph mark */
2034                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
2035                 if (ch_len == 1 && *cbuf == '\n')
2036                         goto compose_end; /* on the paragraph mark */
2037         }
2038
2039         /* find paragraph start. */
2040         line_end = quoted = 0;
2041         for (p_start = cur_pos; p_start >= 0; --p_start) {
2042                 GET_CHAR(p_start, cbuf, ch_len);
2043                 if (ch_len == 1 && *cbuf == '\n') {
2044                         if (quoted)
2045                                 goto compose_end; /* quoted part */
2046                         if (line_end) {
2047                                 p_start += 2;
2048                                 break;
2049                         }
2050                         line_end = 1;
2051                 } else {
2052                         if (ch_len == 1 && strchr(">:#", *cbuf))
2053                                 quoted = 1;
2054                         else if (ch_len != 1 || !isspace(*cbuf))
2055                                 quoted = 0;
2056
2057                         line_end = 0;
2058                 }
2059         }
2060         if (p_start < 0)
2061                 p_start = 0;
2062
2063         /* find paragraph end. */
2064         line_end = 0;
2065         for (p_end = cur_pos; p_end < text_len; p_end++) {
2066                 GET_CHAR(p_end, cbuf, ch_len);
2067                 if (ch_len == 1 && *cbuf == '\n') {
2068                         if (line_end) {
2069                                 p_end -= 1;
2070                                 break;
2071                         }
2072                         line_end = 1;
2073                 } else {
2074                         if (line_end && ch_len == 1 && strchr(">:#", *cbuf))
2075                                 goto compose_end; /* quoted part */
2076
2077                         line_end = 0;
2078                 }
2079         }
2080         if (p_end >= text_len)
2081                 p_end = text_len;
2082
2083         if (p_start >= p_end)
2084                 goto compose_end;
2085
2086         line_len = cur_len = 0;
2087         last_ch_len = 0;
2088         last_ch = '\0';
2089         line_pos = p_start;
2090         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2091                 guint space = 0;
2092
2093                 GET_CHAR(cur_pos, cbuf, ch_len);
2094
2095                 if (ch_len < 0) {
2096                         cbuf[0] = '\0';
2097                         ch_len = 1;
2098                 }
2099
2100                 if (ch_len == 1 && isspace(*cbuf))
2101                         space = 1;
2102
2103                 if (ch_len == 1 && *cbuf == '\n') {
2104                         guint replace = 0;
2105                         if (last_ch_len == 1 && !isspace(last_ch)) {
2106                                 if (cur_pos + 1 < p_end) {
2107                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2108                                         if (ch_len == 1 && !isspace(*cbuf))
2109                                                 replace = 1;
2110                                 }
2111                         }
2112                         gtk_stext_set_point(text, cur_pos + 1);
2113                         gtk_stext_backward_delete(text, 1);
2114                         if (replace) {
2115                                 gtk_stext_set_point(text, cur_pos);
2116                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2117                                 space = 1;
2118                         }
2119                         else {
2120                                 p_end--;
2121                                 cur_pos--;
2122                                 continue;
2123                         }
2124                 }
2125
2126                 last_ch_len = ch_len;
2127                 last_ch = *cbuf;
2128
2129                 if (space) {
2130                         line_pos = cur_pos + 1;
2131                         line_len = cur_len + ch_len;
2132                 }
2133
2134                 if (cur_len + ch_len > prefs_common.linewrap_len &&
2135                     line_len > 0) {
2136                         gint tlen = ch_len;
2137
2138                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2139                         if (ch_len == 1 && isspace(*cbuf)) {
2140                                 gtk_stext_set_point(text, line_pos);
2141                                 gtk_stext_backward_delete(text, 1);
2142                                 p_end--;
2143                                 cur_pos--;
2144                                 line_pos--;
2145                                 cur_len--;
2146                                 line_len--;
2147                         }
2148                         ch_len = tlen;
2149
2150                         gtk_stext_set_point(text, line_pos);
2151                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2152                         p_end++;
2153                         cur_pos++;
2154                         line_pos++;
2155                         cur_len = cur_len - line_len + ch_len;
2156                         line_len = 0;
2157                         continue;
2158                 }
2159
2160                 if (ch_len > 1) {
2161                         line_pos = cur_pos + 1;
2162                         line_len = cur_len + ch_len;
2163                 }
2164                 cur_len += ch_len;
2165         }
2166
2167 compose_end:
2168         gtk_stext_thaw(text);
2169 }
2170
2171 /* return indent length */
2172 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2173 {
2174         gint indent_len = 0;
2175         gint i, ch_len;
2176         gchar cbuf[MB_LEN_MAX];
2177
2178         for (i = start_pos; i < text_len; i++) {
2179                 GET_CHAR(i, cbuf, ch_len);
2180                 if (ch_len > 1)
2181                         break;
2182                 /* allow space, tab, > or | */
2183                 if (cbuf[0] != ' ' && cbuf[0] != '\t' &&
2184                     cbuf[0] != '>' && cbuf[0] != '|')
2185                         break;
2186                 indent_len++;
2187         }
2188
2189         return indent_len;
2190 }
2191
2192 /* insert quotation string when line was wrapped */
2193 static guint ins_quote(GtkSText *text, guint quote_len, guint indent_len,
2194                        guint prev_line_pos, guint text_len,
2195                        gchar *quote_fmt)
2196 {
2197         guint i, ins_len;
2198         gchar ch;
2199
2200         if (indent_len) {
2201                 for (i = 0; i < indent_len; i++) {
2202                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2203                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2204                 }
2205                 ins_len = indent_len;
2206         } else {
2207                 gtk_stext_insert(text, NULL, NULL, NULL, quote_fmt, quote_len);
2208                 ins_len = quote_len;
2209         }
2210
2211         return ins_len;
2212 }
2213
2214 #undef WRAP_DEBUG
2215 #ifdef WRAP_DEBUG
2216 /* Darko: used when I debug wrapping */
2217 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2218 {
2219         gint i;
2220         gchar ch;
2221
2222         printf("%d [", pos);
2223         for (i = pos; i < tlen; i++) {
2224                 ch = GTK_STEXT_INDEX(text, i);
2225                 if (breakoncr && ch == '\n')
2226                         break;
2227                 printf("%c", ch);
2228         }
2229         printf("]\n");
2230 }
2231 #endif
2232
2233 static void compose_wrap_line_all(Compose *compose)
2234 {
2235         GtkSText *text = GTK_STEXT(compose->text);
2236         guint tlen;
2237         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2238         gint line_len = 0, cur_len = 0;
2239         gint ch_len;
2240         gboolean is_new_line = TRUE, do_delete = FALSE;
2241         guint qlen = 0, i_len = 0;
2242         guint linewrap_quote = prefs_common.linewrap_quote;
2243         guint linewrap_len = prefs_common.linewrap_len;
2244         gchar *qfmt = prefs_common.quotemark;
2245         gchar cbuf[MB_LEN_MAX];
2246
2247         gtk_stext_freeze(text);
2248
2249         /* make text buffer contiguous */
2250         /* gtk_stext_compact_buffer(text); */
2251
2252         tlen = gtk_stext_get_length(text);
2253
2254         for (; cur_pos < tlen; cur_pos++) {
2255                 /* mark position of new line - needed for quotation wrap */
2256                 if (is_new_line) {
2257                         if (linewrap_quote) {
2258                                 qlen = gtkut_stext_str_compare
2259                                         (text, cur_pos, tlen, qfmt);
2260                                 if (qlen)
2261                                         i_len = get_indent_length
2262                                                 (text, cur_pos, tlen);
2263                                 else
2264                                         i_len = 0;
2265                         }
2266                         is_new_line = FALSE;
2267                         p_pos = cur_pos;
2268 #ifdef WRAP_DEBUG
2269                         printf("new line i_len=%d qlen=%d p_pos=", i_len, qlen);
2270                         dump_text(text, p_pos, tlen, 1);
2271 #endif
2272                 }
2273
2274                 GET_CHAR(cur_pos, cbuf, ch_len);
2275
2276                 /* fix line length for tabs */
2277                 if (ch_len == 1 && *cbuf == '\t') {
2278                         guint tab_width = text->default_tab_width;
2279                         guint tab_offset = line_len % tab_width;
2280
2281 #ifdef WRAP_DEBUG
2282                         printf("found tab at pos=%d line_len=%d ", cur_pos,
2283                                 line_len);
2284 #endif
2285                         if (tab_offset) {
2286                                 line_len += tab_width - tab_offset - 1;
2287                                 cur_len = line_len;
2288                         }
2289 #ifdef WRAP_DEBUG
2290                         printf("new_len=%d\n", line_len);
2291 #endif
2292                 }
2293
2294                 /* we have encountered line break */
2295                 if (ch_len == 1 && *cbuf == '\n') {
2296                         gint clen;
2297                         guint ilen;
2298                         gchar cb[MB_CUR_MAX];
2299
2300 #ifdef WRAP_DEBUG
2301                         printf("found CR at %d next line is ", cur_pos);
2302                         dump_text(text, cur_pos + 1, tlen, 1);
2303 #endif
2304                         /* if it's just quotation + newline skip it */
2305                         if (i_len && (cur_pos + 1 < tlen)) {
2306                                 /* check if text at new line matches indent */
2307                                 ilen =  gtkut_stext_str_compare_n
2308                                         (text, cur_pos + 1, p_pos, i_len, tlen);
2309                                 if (cur_pos + ilen < tlen) {
2310                                         GET_CHAR(cur_pos + ilen + 1, cb, clen);
2311                                         /* no need to join the lines */
2312                                         if (clen == 1 && cb[0] == '\n')
2313                                                 do_delete = FALSE;
2314                                 }
2315                         /* if it's just newline skip it */
2316                         } else if (do_delete && (cur_pos + 1 < tlen)) {
2317                                 GET_CHAR(cur_pos + 1, cb, clen);
2318                                 /* no need to join the lines */
2319                                 if (clen == 1 && cb[0] == '\n')
2320                                         do_delete = FALSE;
2321                         }
2322
2323 #ifdef WRAP_DEBUG
2324                         printf("qlen=%d l_len=%d wrap_len=%d do_del=%d\n",
2325                                 qlen, line_len, linewrap_len, do_delete);
2326 #endif
2327                         /* should we delete to perform smart wrapping */
2328                         if (line_len < linewrap_len && do_delete) {
2329                                 /* get rid of newline */
2330                                 gtk_stext_set_point(text, cur_pos);
2331                                 gtk_stext_forward_delete(text, 1);
2332                                 tlen--;
2333
2334                                 /* if text starts with quote fmt or with
2335                                    indent string, delete them */
2336                                 if (i_len) {
2337                                         ilen =  gtkut_stext_str_compare_n
2338                                                 (text, cur_pos, p_pos, i_len,
2339                                                  tlen);
2340                                         if (ilen) {
2341                                                 gtk_stext_forward_delete
2342                                                         (text, ilen);
2343                                                 tlen -= ilen;
2344                                         }
2345                                 } else if (qlen) {
2346                                         if (gtkut_stext_str_compare
2347                                             (text, cur_pos, tlen, qfmt)) {
2348                                                 gtk_stext_forward_delete
2349                                                         (text, qlen);
2350                                                 tlen -= qlen;
2351                                         }
2352                                 }
2353
2354                                 GET_CHAR(cur_pos, cb, clen);
2355
2356                                 /* insert space if it's alphanumeric */
2357                                 if ((cur_pos != line_pos) &&
2358                                     ((clen > 1) || isalnum(cb[0]))) {
2359                                         gtk_stext_insert(text, NULL, NULL,
2360                                                         NULL, " ", 1);
2361                                         /* gtk_stext_compact_buffer(text); */
2362                                         tlen++;
2363                                 }
2364
2365                                 /* and start over with current line */
2366                                 cur_pos = p_pos - 1;
2367                                 line_pos = cur_pos;
2368                                 line_len = cur_len = 0;
2369                                 qlen = 0;
2370                                 do_delete = FALSE;
2371                                 is_new_line = TRUE;
2372 #ifdef WRAP_DEBUG
2373                                 printf("after delete l_pos=");
2374                                 dump_text(text, line_pos, tlen, 1);
2375 #endif
2376                                 continue;
2377                         }
2378
2379                         /* mark new line beginning */
2380                         line_pos = cur_pos + 1;
2381                         line_len = cur_len = 0;
2382                         qlen = 0;
2383                         do_delete = FALSE;
2384                         is_new_line = TRUE;
2385                         continue;
2386                 }
2387
2388                 if (ch_len < 0) {
2389                         cbuf[0] = '\0';
2390                         ch_len = 1;
2391                 }
2392
2393                 /* possible line break */
2394                 if (ch_len == 1 && isspace(*cbuf)) {
2395                         line_pos = cur_pos + 1;
2396                         line_len = cur_len + ch_len;
2397                 }
2398
2399                 /* are we over wrapping length set in preferences ? */
2400                 if (cur_len + ch_len > linewrap_len) {
2401                         gint clen;
2402
2403 #ifdef WRAP_DEBUG
2404                         printf("should wrap cur_pos=%d ", cur_pos);
2405                         dump_text(text, p_pos, tlen, 1);
2406                         dump_text(text, line_pos, tlen, 1);
2407 #endif
2408                         /* force wrapping if it is one long word but not URL */
2409                         if (line_pos - p_pos <= i_len)
2410                                 if (!gtkut_stext_is_uri_string
2411                                     (text, line_pos, tlen))
2412                                         line_pos = cur_pos - 1;
2413 #ifdef WRAP_DEBUG
2414                         printf("new line_pos=%d\n", line_pos);
2415 #endif
2416
2417                         GET_CHAR(line_pos - 1, cbuf, clen);
2418
2419                         /* if next character is space delete it */
2420                         if (clen == 1 && isspace(*cbuf)) {
2421                                 if (p_pos + i_len != line_pos ||
2422                                     !gtkut_stext_is_uri_string
2423                                         (text, line_pos, tlen)) {
2424                                         gtk_stext_set_point(text, line_pos);
2425                                         gtk_stext_backward_delete(text, 1);
2426                                         tlen--;
2427                                         cur_pos--;
2428                                         line_pos--;
2429                                         cur_len--;
2430                                         line_len--;
2431                                 }
2432                         }
2433
2434                         /* if it is URL at beginning of line don't wrap */
2435                         if (p_pos + i_len == line_pos &&
2436                             gtkut_stext_is_uri_string(text, line_pos, tlen)) {
2437 #ifdef WRAP_DEBUG
2438                                 printf("found URL at ");
2439                                 dump_text(text, line_pos, tlen, 1);
2440 #endif
2441                                 continue;
2442                         }
2443
2444                         /* insert CR */
2445                         gtk_stext_set_point(text, line_pos);
2446                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2447                         /* gtk_stext_compact_buffer(text); */
2448                         tlen++;
2449                         line_pos++;
2450                         /* for loop will increase it */
2451                         cur_pos = line_pos - 1;
2452                         /* start over with current line */
2453                         is_new_line = TRUE;
2454                         line_len = 0;
2455                         cur_len = 0;
2456                         do_delete = TRUE;
2457 #ifdef WRAP_DEBUG
2458                         printf("after CR insert ");
2459                         dump_text(text, line_pos, tlen, 1);
2460                         dump_text(text, cur_pos, tlen, 1);
2461 #endif
2462
2463                         /* should we insert quotation ? */
2464                         if (linewrap_quote && qlen) {
2465                                 /* only if line is not already quoted  */
2466                                 if (!gtkut_stext_str_compare
2467                                         (text, line_pos, tlen, qfmt)) {
2468                                         guint ins_len;
2469
2470                                         if (line_pos - p_pos > i_len) {
2471                                                 ins_len = ins_quote
2472                                                         (text, qlen, i_len,
2473                                                          p_pos, tlen, qfmt);
2474
2475                                                 /* gtk_stext_compact_buffer(text); */
2476                                                 tlen += ins_len;
2477                                         }
2478 #ifdef WRAP_DEBUG
2479                                         printf("after quote insert ");
2480                                         dump_text(text, line_pos, tlen, 1);
2481 #endif
2482                                 }
2483                         }
2484                         continue;
2485                 }
2486
2487                 if (ch_len > 1) {
2488                         line_pos = cur_pos + 1;
2489                         line_len = cur_len + ch_len;
2490                 }
2491                 /* advance to next character in buffer */
2492                 cur_len += ch_len;
2493         }
2494
2495         gtk_stext_thaw(text);
2496 }
2497
2498 #undef GET_CHAR
2499
2500 static void compose_set_title(Compose *compose)
2501 {
2502         gchar *str;
2503         gchar *edited;
2504
2505         edited = compose->modified ? _(" [Edited]") : "";
2506         if (compose->account && compose->account->address)
2507                 str = g_strdup_printf(_("%s - Compose message%s"),
2508                                       compose->account->address, edited);
2509         else
2510                 str = g_strdup_printf(_("Compose message%s"), edited);
2511         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2512         g_free(str);
2513 }
2514
2515 /**
2516  * compose_current_mail_account:
2517  * 
2518  * Find a current mail account (the currently selected account, or the
2519  * default account, if a news account is currently selected).  If a
2520  * mail account cannot be found, display an error message.
2521  * 
2522  * Return value: Mail account, or NULL if not found.
2523  **/
2524 static PrefsAccount *
2525 compose_current_mail_account(void)
2526 {
2527         PrefsAccount *ac;
2528
2529         if (cur_account && cur_account->protocol != A_NNTP)
2530                 ac = cur_account;
2531         else {
2532                 ac = account_get_default();
2533                 if (!ac || ac->protocol == A_NNTP) {
2534                         alertpanel_error(_("Account for sending mail is not specified.\n"
2535                                            "Please select a mail account before sending."));
2536                         return NULL;
2537                 }
2538         }
2539         return ac;
2540 }
2541
2542 gboolean compose_check_for_valid_recipient(Compose *compose) {
2543         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
2544         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
2545         gboolean recipient_found = FALSE;
2546         GSList *list;
2547         gchar **strptr;
2548
2549         /* free to and newsgroup list */
2550         slist_free_strings(compose->to_list);
2551         g_slist_free(compose->to_list);
2552         compose->to_list = NULL;
2553                         
2554         slist_free_strings(compose->newsgroup_list);
2555         g_slist_free(compose->newsgroup_list);
2556         compose->newsgroup_list = NULL;
2557
2558         /* search header entries for to and newsgroup entries */
2559         for(list = compose->header_list; list; list = list->next) {
2560                 gchar *header;
2561                 gchar *entry;
2562                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry));
2563                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
2564                 g_strstrip(entry);
2565                 if(entry[0] != '\0') {
2566                         for(strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
2567                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2568                                         compose->to_list = address_list_append(compose->to_list, entry);
2569                                         recipient_found = TRUE;
2570                                 }
2571                         }
2572                         for(strptr = recipient_headers_news; *strptr != NULL; strptr++) {
2573                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2574                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
2575                                         recipient_found = TRUE;
2576                                 }
2577                         }
2578                 }
2579                 g_free(entry);
2580         }
2581         return recipient_found;
2582 }
2583
2584 gint compose_send(Compose *compose)
2585 {
2586         gint msgnum;
2587         FolderItem *folder;
2588         gint val;
2589
2590         val = compose_queue(compose, &msgnum, &folder);
2591         if (val) {
2592                 alertpanel_error(_("Could not queue message for sending"));
2593                 return -1;
2594         }
2595         
2596         val = procmsg_send_message_queue(folder_item_fetch_msg(folder, msgnum));
2597         if(!val) {
2598                 folder_item_remove_msg(folder, msgnum);
2599                 folderview_update_item(folder, TRUE);
2600         }
2601
2602         return val;
2603 }
2604
2605 #if 0 /* compose restructure */
2606 gint compose_send(Compose *compose)
2607 {
2608         gchar tmp[MAXPATHLEN + 1];
2609         gint ok = 0;
2610         static gboolean lock = FALSE;
2611
2612         if (lock) return 1;
2613
2614         g_return_val_if_fail(compose->account != NULL, -1);
2615         g_return_val_if_fail(compose->orig_account != NULL, -1);
2616
2617         lock = TRUE;
2618
2619         if(!compose_check_for_valid_recipient(compose)) {
2620                 alertpanel_error(_("Recipient is not specified."));
2621                 lock = FALSE;
2622                 return 1;
2623         }
2624
2625         /* write to temporary file */
2626         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
2627                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
2628
2629         if (prefs_common.linewrap_at_send)
2630                 compose_wrap_line_all(compose);
2631
2632         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2633                 lock = FALSE;
2634                 return -1;
2635         }
2636
2637         if (!compose->to_list && !compose->newsgroup_list) {
2638                 g_warning(_("can't get recipient list."));
2639                 unlink(tmp);
2640                 lock = FALSE;
2641                 return -1;
2642         }
2643
2644         if (compose->to_list) {
2645                 PrefsAccount *ac;
2646
2647 #if 0 /* NEW COMPOSE GUI */
2648                 if (compose->account->protocol != A_NNTP)
2649                         ac = compose->account;
2650                 else if (compose->orig_account->protocol != A_NNTP)
2651                         ac = compose->orig_account;
2652                 else if (cur_account && cur_account->protocol != A_NNTP)
2653                         ac = cur_account;
2654                 else {
2655                         ac = compose_current_mail_account();
2656                         if (!ac) {
2657                                 unlink(tmp);
2658                                 lock = FALSE;
2659                                 return -1;
2660                         }
2661                 }
2662 #endif
2663                 ac = compose->account;
2664
2665                 ok = send_message(tmp, ac, compose->to_list);
2666                 statusbar_pop_all();
2667         }
2668
2669         if (ok == 0 && compose->newsgroup_list) {
2670                 Folder *folder;
2671
2672                 if (compose->account->protocol == A_NNTP)
2673                         folder = FOLDER(compose->account->folder);
2674                 else
2675                         folder = FOLDER(compose->orig_account->folder);
2676
2677                 ok = news_post(folder, tmp);
2678                 if (ok < 0) {
2679                         alertpanel_error(_("Error occurred while posting the message to %s ."),
2680                                          compose->account->nntp_server);
2681                         unlink(tmp);
2682                         lock = FALSE;
2683                         return -1;
2684                 }
2685         }
2686
2687         /* queue message if failed to send */
2688         if (ok < 0) {
2689                 if (prefs_common.queue_msg) {
2690                         AlertValue val;
2691
2692                         val = alertpanel
2693                                 (_("Queueing"),
2694                                  _("Error occurred while sending the message.\n"
2695                                    "Put this message into queue folder?"),
2696                                  _("OK"), _("Cancel"), NULL);
2697                         if (G_ALERTDEFAULT == val) {
2698                                 ok = compose_queue(compose, tmp);
2699                                 if (ok < 0)
2700                                         alertpanel_error(_("Can't queue the message."));
2701                         }
2702                 } else
2703                         alertpanel_error(_("Error occurred while sending the message."));
2704         } else {
2705                 if (compose->mode == COMPOSE_REEDIT) {
2706                         compose_remove_reedit_target(compose);
2707                         if (compose->targetinfo)
2708                                 folderview_update_item
2709                                         (compose->targetinfo->folder, TRUE);
2710                 }
2711         }
2712
2713         /* save message to outbox */
2714         if (ok == 0 && prefs_common.savemsg) {
2715                 if (compose_save_to_outbox(compose, tmp) < 0)
2716                         alertpanel_error
2717                                 (_("Can't save the message to outbox."));
2718         }
2719
2720         unlink(tmp);
2721         lock = FALSE;
2722         return ok;
2723 }
2724 #endif
2725
2726 static gboolean compose_use_attach(Compose *compose) {
2727     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
2728 }
2729
2730 static gint compose_bounce_write_headers_from_headerlist(Compose *compose, 
2731                                                          FILE *fp)
2732 {
2733         gchar buf[BUFFSIZE];
2734         gchar *str;
2735         gboolean first_address;
2736         GSList *list;
2737         ComposeHeaderEntry *headerentry;
2738         gchar *headerentryname;
2739         gchar *header_w_colon;
2740         gchar *cc_hdr;
2741         gchar *to_hdr;
2742
2743         debug_print(_("Writing bounce header\n"));
2744
2745         header_w_colon = g_strconcat("To:", NULL);
2746         to_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
2747         header_w_colon = g_strconcat("Cc:", NULL);
2748         cc_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
2749         
2750         first_address = TRUE;
2751         for(list = compose->header_list; list; list = list->next) {
2752                 headerentry = ((ComposeHeaderEntry *)list->data);
2753                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
2754
2755                 if(g_strcasecmp(headerentryname, cc_hdr) == 0 
2756                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
2757                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
2758                         Xstrdup_a(str, str, return -1);
2759                         g_strstrip(str);
2760                         if(str[0] != '\0') {
2761                                 compose_convert_header
2762                                         (buf, sizeof(buf), str,
2763                                         strlen("Resent-To") + 2);
2764                                 if(first_address) {
2765                                         fprintf(fp, "Resent-To: ");
2766                                         first_address = FALSE;
2767                                 } else {
2768                                         fprintf(fp, ",");
2769                                 }
2770                                 fprintf(fp, "%s", buf);
2771                         }
2772                 }
2773         }
2774         /* if(!first_address) { */
2775         fprintf(fp, "\n");
2776         /* } */
2777
2778         return(0);
2779 }
2780
2781 static gint compose_bounce_write_headers(Compose *compose, FILE *fp)
2782 {
2783         gchar buf[BUFFSIZE];
2784         gchar *str;
2785         /* struct utsname utsbuf; */
2786
2787         g_return_val_if_fail(fp != NULL, -1);
2788         g_return_val_if_fail(compose->account != NULL, -1);
2789         g_return_val_if_fail(compose->account->address != NULL, -1);
2790
2791         /* Date */
2792         get_rfc822_date(buf, sizeof(buf));
2793         fprintf(fp, "Resent-Date: %s\n", buf);
2794
2795         /* From */
2796         if (compose->account->name && *compose->account->name) {
2797                 compose_convert_header
2798                         (buf, sizeof(buf), compose->account->name,
2799                          strlen("From: "));
2800                 fprintf(fp, "Resent-From: %s <%s>\n",
2801                         buf, compose->account->address);
2802         } else
2803                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
2804
2805         /* To */
2806         compose_bounce_write_headers_from_headerlist(compose, fp);
2807
2808         /* separator between header and body */
2809         fputs("\n", fp);
2810
2811         return 0;
2812 }
2813
2814 static gint compose_bounce_write_to_file(Compose *compose, const gchar *file)
2815 {
2816         FILE *fp;
2817         FILE *fdest;
2818         size_t len;
2819         gchar buf[BUFFSIZE];
2820
2821         if ((fp = fopen(compose->bounce_filename, "r")) == NULL) {
2822                 FILE_OP_ERROR(file, "fopen");
2823                 return -1;
2824         }
2825
2826         if ((fdest = fopen(file, "w")) == NULL) {
2827                 FILE_OP_ERROR(file, "fopen");
2828                 fclose(fp);
2829                 return -1;
2830         }
2831
2832         /* chmod for security */
2833         if (change_file_mode_rw(fdest, file) < 0) {
2834                 FILE_OP_ERROR(file, "chmod");
2835                 g_warning(_("can't change file mode\n"));
2836         }
2837
2838         while (procheader_get_unfolded_line(buf, sizeof(buf), fp)) {
2839                 /* should filter returnpath, delivered-to */
2840                 if ((g_strncasecmp(buf, "Return-Path:",
2841                                    strlen("Return-Path:")) == 0)
2842                     || (g_strncasecmp(buf, "Delivered-To:",
2843                                       strlen("Delivered-To:")) == 0))
2844                         continue;
2845
2846                 if (fputs(buf, fdest) == -1)
2847                         goto error;
2848
2849                 if (g_strncasecmp(buf, "From:", strlen("From:")) == 0) {
2850                         fputs(" (by way of ", fdest);
2851                         if (compose->account->name
2852                             && *compose->account->name) {
2853                                 compose_convert_header
2854                                         (buf, sizeof(buf),
2855                                          compose->account->name,
2856                                          strlen("From: "));
2857                                 fprintf(fdest, "%s <%s>",
2858                                         buf, compose->account->address);
2859                         } else
2860                                 fprintf(fdest, "%s",
2861                                         compose->account->address);
2862                         fputs(")", fdest);
2863                 }
2864
2865                 if (fputs("\n", fdest) == -1)
2866                         goto error;
2867         }
2868
2869         compose_bounce_write_headers(compose, fdest);
2870
2871         while ((len = fread(buf, sizeof(gchar), BUFFSIZE, fp)) > 0) {
2872                 if (fwrite(buf, sizeof(gchar), len, fdest) == -1)
2873                         goto error;
2874         }
2875
2876         fclose(fdest);
2877         fclose(fp);
2878
2879         return 0;
2880  error:
2881         fclose(fdest);
2882         fclose(fp);
2883
2884         return -1;
2885 }
2886
2887
2888 #ifdef USE_GPGME
2889 /*
2890  * interfaces to rfc2015 to keep out the prefs stuff there.
2891  * returns 0 on success and -1 on error. */
2892 static int compose_create_signers_list (Compose *compose, GSList **pkey_list)
2893 {
2894         const char *keyid = NULL;
2895         GSList *key_list;
2896
2897         switch (compose->account->sign_key) {
2898         case SIGN_KEY_DEFAULT:
2899                 *pkey_list = NULL;
2900                 return 0;               /* nothing to do */
2901
2902         case SIGN_KEY_BY_FROM:
2903                 keyid = compose->account->address;
2904                 break;
2905
2906         case SIGN_KEY_CUSTOM:
2907                 keyid = compose->account->sign_key_id;
2908                 break;
2909
2910         default:
2911                 g_assert_not_reached ();
2912         }
2913
2914         key_list = rfc2015_create_signers_list(keyid);
2915
2916         if (!key_list) {
2917             alertpanel_error("Could not find any key associated with currently "
2918                                 "selected keyid `%s'!", keyid);
2919             return -1;
2920         }
2921         
2922         *pkey_list = key_list;
2923         return 0;
2924 }
2925 #endif /* USE_GPGME */
2926
2927 static gint compose_write_to_file(Compose *compose, const gchar *file,
2928                                   gboolean is_draft)
2929 {
2930         FILE *fp;
2931         size_t len;
2932         gchar *chars;
2933         gchar *buf;
2934         const gchar *out_codeset;
2935         EncodingType encoding;
2936
2937         if ((fp = fopen(file, "w")) == NULL) {
2938                 FILE_OP_ERROR(file, "fopen");
2939                 return -1;
2940         }
2941
2942         /* chmod for security */
2943         if (change_file_mode_rw(fp, file) < 0) {
2944                 FILE_OP_ERROR(file, "chmod");
2945                 g_warning(_("can't change file mode\n"));
2946         }
2947
2948         /* get all composed text */
2949         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2950         len = strlen(chars);
2951         if (is_ascii_str(chars)) {
2952                 buf = g_strdup(chars);
2953                 out_codeset = CS_US_ASCII;
2954                 encoding = ENC_7BIT;
2955         } else {
2956                 const gchar *src_codeset;
2957
2958                 out_codeset = conv_get_outgoing_charset_str();
2959                 if (!strcasecmp(out_codeset, CS_US_ASCII))
2960                         out_codeset = CS_ISO_8859_1;
2961                 encoding = procmime_get_encoding_for_charset(out_codeset);
2962
2963                 src_codeset = conv_get_current_charset_str();
2964                 /* if current encoding is US-ASCII, set it the same as
2965                    outgoing one to prevent code conversion failure */
2966                 if (!strcasecmp(src_codeset, CS_US_ASCII))
2967                         src_codeset = out_codeset;
2968
2969                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
2970                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
2971
2972                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
2973                 if (!buf) {
2974                         g_free(chars);
2975                         fclose(fp);
2976                         unlink(file);
2977                         alertpanel_error(_("Can't convert the codeset of the message."));
2978                         return -1;
2979                 }
2980         }
2981         g_free(chars);
2982
2983         /* write headers */
2984         if (compose_write_headers
2985                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
2986                 g_warning(_("can't write headers\n"));
2987                 fclose(fp);
2988                 /* unlink(file); */
2989                 g_free(buf);
2990                 return -1;
2991         }
2992
2993         if (compose_use_attach(compose)) {
2994 #if USE_GPGME
2995             /* This prolog message is ignored by mime software and
2996              * because it would make our signing/encryption task
2997              * tougher, we don't emit it in that case */
2998             if (!compose->use_signing && !compose->use_encryption)
2999 #endif
3000                 fputs("This is a multi-part message in MIME format.\n", fp);
3001
3002                 fprintf(fp, "\n--%s\n", compose->boundary);
3003                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
3004                         out_codeset);
3005                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3006                         procmime_get_encoding_str(encoding));
3007                 fputc('\n', fp);
3008         }
3009
3010         /* write body */
3011         len = strlen(buf);
3012         if (encoding == ENC_BASE64) {
3013                 gchar outbuf[B64_BUFFSIZE];
3014                 gint i, l;
3015
3016                 for (i = 0; i < len; i += B64_LINE_SIZE) {
3017                         l = MIN(B64_LINE_SIZE, len - i);
3018                         to64frombits(outbuf, buf + i, l);
3019                         fputs(outbuf, fp);
3020                         fputc('\n', fp);
3021                 }
3022         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
3023                 FILE_OP_ERROR(file, "fwrite");
3024                 fclose(fp);
3025                 unlink(file);
3026                 g_free(buf);
3027                 return -1;
3028         }
3029         g_free(buf);
3030
3031         if (compose_use_attach(compose))
3032                 compose_write_attach(compose, fp);
3033
3034         if (fclose(fp) == EOF) {
3035                 FILE_OP_ERROR(file, "fclose");
3036                 unlink(file);
3037                 return -1;
3038         }
3039
3040 #if USE_GPGME
3041         if (compose->use_signing) {
3042                 GSList *key_list;
3043                 
3044                 if (compose_create_signers_list(compose, &key_list) == -1 ||
3045                         rfc2015_sign(file, key_list) < 0) {
3046                     
3047                         unlink(file);
3048                         return -1;
3049                 }
3050         }
3051         if (compose->use_encryption) {
3052                 if (rfc2015_encrypt(file, compose->to_list, compose->account->ascii_armored) < 0) {
3053                         unlink(file);
3054                         return -1;
3055                 }
3056         }
3057 #endif /* USE_GPGME */
3058
3059         return 0;
3060 }
3061
3062 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3063 {
3064         FILE *fp;
3065         size_t len;
3066         gchar *chars;
3067
3068         if ((fp = fopen(file, "w")) == NULL) {
3069                 FILE_OP_ERROR(file, "fopen");
3070                 return -1;
3071         }
3072
3073         /* chmod for security */
3074         if (change_file_mode_rw(fp, file) < 0) {
3075                 FILE_OP_ERROR(file, "chmod");
3076                 g_warning(_("can't change file mode\n"));
3077         }
3078
3079         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3080
3081         /* write body */
3082         len = strlen(chars);
3083         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3084                 FILE_OP_ERROR(file, "fwrite");
3085                 g_free(chars);
3086                 fclose(fp);
3087                 unlink(file);
3088                 return -1;
3089         }
3090
3091         g_free(chars);
3092
3093         if (fclose(fp) == EOF) {
3094                 FILE_OP_ERROR(file, "fclose");
3095                 unlink(file);
3096                 return -1;
3097         }
3098         return 0;
3099 }
3100
3101 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
3102 {
3103         FolderItem *outbox;
3104         gchar *path;
3105         gint num;
3106         FILE *fp;
3107
3108         debug_print(_("saving sent message...\n"));
3109
3110         outbox = folder_get_default_outbox();
3111         path = folder_item_get_path(outbox);
3112         if (!is_dir_exist(path))
3113                 make_dir_hier(path);
3114
3115         folder_item_scan(outbox);
3116         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
3117                 g_free(path);
3118                 g_warning(_("can't save message\n"));
3119                 return -1;
3120         }
3121
3122         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
3123                 g_warning(_("can't open mark file\n"));
3124         else {
3125                 MsgInfo newmsginfo;
3126
3127                 newmsginfo.msgnum = num;
3128                 newmsginfo.flags.perm_flags = 0;
3129                 newmsginfo.flags.tmp_flags = 0;
3130                 procmsg_write_flags(&newmsginfo, fp);
3131                 fclose(fp);
3132         }
3133         g_free(path);
3134
3135         return 0;
3136 }
3137
3138 static gint compose_remove_reedit_target(Compose *compose)
3139 {
3140         FolderItem *item;
3141         MsgInfo *msginfo = compose->targetinfo;
3142
3143         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3144         if (!msginfo) return -1;
3145
3146         item = msginfo->folder;
3147         g_return_val_if_fail(item != NULL, -1);
3148
3149         folder_item_scan(item);
3150         if (procmsg_msg_exist(msginfo) &&
3151             (item->stype == F_DRAFT || item->stype == F_QUEUE)) {
3152                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3153                         g_warning(_("can't remove the old message\n"));
3154                         return -1;
3155                 }
3156         }
3157
3158         return 0;
3159 }
3160
3161
3162 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3163 {
3164         FolderItem *queue;
3165         gchar *tmp, *tmp2, *queue_path;
3166         FILE *fp, *src_fp;
3167         GSList *cur;
3168         gchar buf[BUFFSIZE];
3169         gint num;
3170         static gboolean lock = FALSE;
3171         PrefsAccount *mailac = NULL, *newsac = NULL;
3172         
3173         debug_print(_("queueing message...\n"));
3174         g_return_val_if_fail(compose->account != NULL, -1);
3175         g_return_val_if_fail(compose->orig_account != NULL, -1);
3176
3177         lock = TRUE;
3178         
3179         if(!compose_check_for_valid_recipient(compose)) {
3180                 alertpanel_error(_("Recipient is not specified."));
3181                 lock = FALSE;
3182                 return -1;
3183         }
3184                                                                         
3185         if (!compose->to_list && !compose->newsgroup_list) {
3186                 g_warning(_("can't get recipient list."));
3187                 lock = FALSE;
3188                 return -1;
3189         }
3190
3191         if(compose->to_list) {
3192                 if (compose->account->protocol != A_NNTP)
3193                         mailac = compose->account;
3194                 else if (compose->orig_account->protocol != A_NNTP)
3195                         mailac = compose->orig_account;
3196                 else if (cur_account && cur_account->protocol != A_NNTP)
3197                         mailac = cur_account;
3198                 else if (!(mailac = compose_current_mail_account())) {
3199                         lock = FALSE;
3200                         alertpanel_error(_("No account for sending mails available!"));
3201                         return -1;
3202                 }
3203         }
3204
3205         if(compose->newsgroup_list) {
3206                 if (compose->account->protocol == A_NNTP)
3207                         newsac = compose->account;
3208                 else if(!(newsac = compose->orig_account) || (newsac->protocol != A_NNTP)) {
3209                         lock = FALSE;
3210                         alertpanel_error(_("No account for posting news available!"));
3211                         return -1;
3212                 }                       
3213         }
3214
3215         if (prefs_common.linewrap_at_send)
3216                 compose_wrap_line_all(compose);
3217                         
3218         /* write to temporary file */
3219         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3220                                       G_DIR_SEPARATOR, (gint)compose);
3221
3222         if (compose->bounce_filename != NULL) {
3223                 if (compose_bounce_write_to_file(compose, tmp2) < 0) {
3224                         unlink(tmp2);
3225                         lock = FALSE;
3226                         return -1;
3227                 }
3228         }
3229         else {
3230                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3231                         unlink(tmp2);
3232                         lock = FALSE;
3233                         return -1;
3234                 }
3235         }
3236
3237         /* add queue header */
3238         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3239                                       G_DIR_SEPARATOR, (gint)compose);
3240         if ((fp = fopen(tmp, "w")) == NULL) {
3241                 FILE_OP_ERROR(tmp, "fopen");
3242                 g_free(tmp);
3243                 return -1;
3244         }
3245         if ((src_fp = fopen(tmp2, "r")) == NULL) {
3246                 FILE_OP_ERROR(tmp2, "fopen");
3247                 fclose(fp);
3248                 unlink(tmp);
3249                 g_free(tmp);
3250                 unlink(tmp2);
3251                 g_free(tmp2);
3252                 return -1;
3253         }
3254         if (change_file_mode_rw(fp, tmp) < 0) {
3255                 FILE_OP_ERROR(tmp, "chmod");
3256                 g_warning(_("can't change file mode\n"));
3257         }
3258
3259         /* queueing variables */
3260         fprintf(fp, "AF:\n");
3261         fprintf(fp, "NF:0\n");
3262         fprintf(fp, "PS:10\n");
3263         fprintf(fp, "SRH:1\n");
3264         fprintf(fp, "SFN:\n");
3265         fprintf(fp, "DSR:\n");
3266         if (compose->msgid)
3267                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3268         else
3269                 fprintf(fp, "MID:\n");
3270         fprintf(fp, "CFG:\n");
3271         fprintf(fp, "PT:0\n");
3272         fprintf(fp, "S:%s\n", compose->account->address);
3273         fprintf(fp, "RQ:\n");
3274         if (mailac)
3275                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3276         else
3277                 fprintf(fp, "SSV:\n");
3278         if (newsac)
3279                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3280         else
3281                 fprintf(fp, "NSV:\n");
3282         fprintf(fp, "SSH:\n");
3283         /* write recepient list */
3284         fprintf(fp, "R:");
3285         if(compose->to_list) {
3286                 fprintf(fp, "<%s>", (gchar *)compose->to_list->data);
3287                 for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
3288                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3289         }
3290         fprintf(fp, "\n");
3291         /* write newsgroup list */
3292         fprintf(fp, "NG:");
3293         if(compose->newsgroup_list) {
3294                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3295                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3296                         fprintf(fp, ",%s", (gchar *)cur->data);
3297         }
3298         fprintf(fp, "\n");
3299         /* Sylpheed account IDs */
3300         if(mailac) {
3301                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3302         }
3303         if(newsac) {
3304                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3305         }
3306         /* Save copy folder */
3307         if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3308                 gchar *str;
3309                 
3310                 str = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3311                 fprintf(fp, "SCF:%s\n", str);
3312                 g_free(str);
3313         }
3314         fprintf(fp, "\n");
3315
3316         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3317                 if (fputs(buf, fp) == EOF) {
3318                         FILE_OP_ERROR(tmp, "fputs");
3319                         fclose(fp);
3320                         fclose(src_fp);
3321                         unlink(tmp);
3322                         g_free(tmp);
3323                         unlink(tmp2);
3324                         g_free(tmp2);
3325                         return -1;
3326                 }
3327         }
3328         fclose(src_fp);
3329         if (fclose(fp) == EOF) {
3330                 FILE_OP_ERROR(tmp, "fclose");
3331                 unlink(tmp);
3332                 g_free(tmp);
3333                 unlink(tmp2);
3334                 g_free(tmp2);
3335                 return -1;
3336         }
3337                                                 
3338         /* queue message */
3339         queue = folder_get_default_queue();
3340
3341         folder_item_scan(queue);
3342         queue_path = folder_item_get_path(queue);
3343         if (!is_dir_exist(queue_path))
3344                 make_dir_hier(queue_path);
3345         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3346                 g_warning(_("can't queue the message\n"));
3347                 unlink(tmp);
3348                 g_free(tmp);
3349                 g_free(queue_path);
3350                 return -1;
3351         }
3352         unlink(tmp);
3353         g_free(tmp);
3354         unlink(tmp2);
3355         g_free(tmp2);
3356
3357         if (compose->mode == COMPOSE_REEDIT) {
3358                 compose_remove_reedit_target(compose);
3359                 if (compose->targetinfo &&
3360                     compose->targetinfo->folder != queue)
3361                         folderview_update_item
3362                                 (compose->targetinfo->folder, TRUE);
3363         }
3364
3365         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
3366                 g_warning(_("can't open mark file\n"));
3367         else {
3368                 MsgInfo newmsginfo;
3369
3370                 newmsginfo.msgnum = num;
3371                 newmsginfo.flags.perm_flags = 0;
3372                 newmsginfo.flags.tmp_flags = 0;
3373                 procmsg_write_flags(&newmsginfo, fp);
3374                 fclose(fp);
3375         }
3376         g_free(queue_path);
3377
3378         folder_item_scan(queue);
3379         folderview_update_item(queue, TRUE);
3380
3381         if((msgnum != NULL) && (item != NULL)) {
3382                 *msgnum = num;
3383                 *item = queue;
3384         }
3385
3386         return 0;
3387 }
3388
3389 static void compose_write_attach(Compose *compose, FILE *fp)
3390 {
3391         AttachInfo *ainfo;
3392         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3393         gint row;
3394         FILE *attach_fp;
3395         gchar filename[BUFFSIZE];
3396         gint len;
3397
3398         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3399              row++) {
3400                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
3401                         g_warning(_("Can't open file %s\n"), ainfo->file);
3402                         continue;
3403                 }
3404
3405                 fprintf(fp, "\n--%s\n", compose->boundary);
3406
3407                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3408                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3409                         fprintf(fp, "Content-Disposition: inline\n");
3410                 } else {
3411                         conv_encode_header(filename, sizeof(filename),
3412                                            ainfo->name, 12);
3413                         fprintf(fp, "Content-Type: %s;\n"
3414                                     " name=\"%s\"\n",
3415                                 ainfo->content_type, filename);
3416                         fprintf(fp, "Content-Disposition: attachment;\n"
3417                                     " filename=\"%s\"\n", filename);
3418                 }
3419
3420                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3421                         procmime_get_encoding_str(ainfo->encoding));
3422
3423                 if (ainfo->encoding == ENC_7BIT) {
3424                         gchar buf[BUFFSIZE];
3425
3426                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3427                                 strcrchomp(buf);
3428                                 fputs(buf, fp);
3429                         }
3430                 } else {
3431                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3432
3433                         while ((len = fread(inbuf, sizeof(gchar),
3434                                             B64_LINE_SIZE, attach_fp))
3435                                == B64_LINE_SIZE) {
3436                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
3437                                 fputs(outbuf, fp);
3438                                 fputc('\n', fp);
3439                         }
3440                         if (len > 0 && feof(attach_fp)) {
3441                                 to64frombits(outbuf, inbuf, len);
3442                                 fputs(outbuf, fp);
3443                                 fputc('\n', fp);
3444                         }
3445                 }
3446
3447                 fclose(attach_fp);
3448         }
3449
3450         fprintf(fp, "\n--%s--\n", compose->boundary);
3451 }
3452
3453 #define IS_IN_CUSTOM_HEADER(header) \
3454         (compose->account->add_customhdr && \
3455          custom_header_find(compose->account->customhdr_list, header) != NULL)
3456
3457 static gint compose_write_headers_from_headerlist(Compose *compose, 
3458                                                   FILE *fp, 
3459                                                   gchar *header)
3460 {
3461         gchar buf[BUFFSIZE];
3462         gchar *str, *header_w_colon, *trans_hdr;
3463         gboolean first_address;
3464         GSList *list;
3465         ComposeHeaderEntry *headerentry;
3466         gchar * headerentryname;
3467
3468         if (IS_IN_CUSTOM_HEADER(header)) {
3469                 return 0;
3470         }
3471
3472         debug_print(_("Writing %s-header\n"), header);
3473
3474         header_w_colon = g_strconcat(header, ":", NULL);
3475         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3476
3477         first_address = TRUE;
3478         for(list = compose->header_list; list; list = list->next) {
3479                 headerentry = ((ComposeHeaderEntry *)list->data);
3480                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3481
3482                 if(!g_strcasecmp(trans_hdr, headerentryname)) {
3483                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3484                         Xstrdup_a(str, str, return -1);
3485                         g_strstrip(str);
3486                         if(str[0] != '\0') {
3487                                 compose_convert_header
3488                                         (buf, sizeof(buf), str,
3489                                         strlen(header) + 2);
3490                                 if(first_address) {
3491                                         fprintf(fp, "%s: ", header);
3492                                         first_address = FALSE;
3493                                 } else {
3494                                         fprintf(fp, ",");
3495                                 }
3496                                 fprintf(fp, "%s", buf);
3497                         }
3498                 }
3499         }
3500         if(!first_address) {
3501                 fprintf(fp, "\n");
3502         }
3503
3504         g_free(header_w_colon);
3505
3506         return(0);
3507 }
3508
3509 static gint compose_write_headers(Compose *compose, FILE *fp,
3510                                   const gchar *charset, EncodingType encoding,
3511                                   gboolean is_draft)
3512 {
3513         gchar buf[BUFFSIZE];
3514         gchar *str;
3515         /* struct utsname utsbuf; */
3516
3517         g_return_val_if_fail(fp != NULL, -1);
3518         g_return_val_if_fail(charset != NULL, -1);
3519         g_return_val_if_fail(compose->account != NULL, -1);
3520         g_return_val_if_fail(compose->account->address != NULL, -1);
3521
3522         /* Date */
3523         if (compose->account->add_date) {
3524                 get_rfc822_date(buf, sizeof(buf));
3525                 fprintf(fp, "Date: %s\n", buf);
3526         }
3527
3528         /* From */
3529         if (!IS_IN_CUSTOM_HEADER("From")) {
3530                 if (compose->account->name && *compose->account->name) {
3531                         compose_convert_header
3532                                 (buf, sizeof(buf), compose->account->name,
3533                                  strlen("From: "));
3534                         fprintf(fp, "From: %s <%s>\n",
3535                                 buf, compose->account->address);
3536                 } else
3537                         fprintf(fp, "From: %s\n", compose->account->address);
3538         }
3539         
3540         /* To */
3541         compose_write_headers_from_headerlist(compose, fp, "To");
3542 #if 0 /* NEW COMPOSE GUI */
3543         if (compose->use_to) {
3544                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3545                 if (*str != '\0') {
3546                         Xstrdup_a(str, str, return -1);
3547                         g_strstrip(str);
3548                         if (*str != '\0') {
3549                                 compose->to_list = address_list_append
3550                                         (compose->to_list, str);
3551                                 if (!IS_IN_CUSTOM_HEADER("To")) {
3552                                         compose_convert_header
3553                                                 (buf, sizeof(buf), str,
3554                                                  strlen("To: "));
3555                                         fprintf(fp, "To: %s\n", buf);
3556                                 }
3557                         }
3558                 }
3559         }
3560 #endif
3561
3562         /* Newsgroups */
3563         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
3564 #if 0 /* NEW COMPOSE GUI */
3565         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3566         if (*str != '\0') {
3567                 Xstrdup_a(str, str, return -1);
3568                 g_strstrip(str);
3569                 remove_space(str);
3570                 if (*str != '\0') {
3571                         compose->newsgroup_list =
3572                                 newsgroup_list_append(compose->newsgroup_list,
3573                                                       str);
3574                         if (!IS_IN_CUSTOM_HEADER("Newsgroups")) {
3575                                 compose_convert_header(buf, sizeof(buf), str,
3576                                                        strlen("Newsgroups: "));
3577                                 fprintf(fp, "Newsgroups: %s\n", buf);
3578                         }
3579                 }
3580         }
3581 #endif
3582         /* Cc */
3583         compose_write_headers_from_headerlist(compose, fp, "Cc");
3584 #if 0 /* NEW COMPOSE GUI */
3585         if (compose->use_cc) {
3586                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
3587                 if (*str != '\0') {
3588                         Xstrdup_a(str, str, return -1);
3589                         g_strstrip(str);
3590                         if (*str != '\0') {
3591                                 compose->to_list = address_list_append
3592                                         (compose->to_list, str);
3593                                 if (!IS_IN_CUSTOM_HEADER("Cc")) {
3594                                         compose_convert_header
3595                                                 (buf, sizeof(buf), str,
3596                                                  strlen("Cc: "));
3597                                         fprintf(fp, "Cc: %s\n", buf);
3598                                 }
3599                         }
3600                 }
3601         }
3602 #endif
3603         /* Bcc */
3604         compose_write_headers_from_headerlist(compose, fp, "Bcc");
3605 #if 0 /* NEW COMPOSE GUI */
3606         if (compose->use_bcc) {
3607                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
3608                 if (*str != '\0') {
3609                         Xstrdup_a(str, str, return -1);
3610                         g_strstrip(str);
3611                         if (*str != '\0') {
3612                                 compose->to_list = address_list_append
3613                                         (compose->to_list, str);
3614                                 compose_convert_header(buf, sizeof(buf), str,
3615                                                        strlen("Bcc: "));
3616                                 fprintf(fp, "Bcc: %s\n", buf);
3617                         }
3618                 }
3619         }
3620 #endif
3621
3622         /* Subject */
3623         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3624         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
3625                 Xstrdup_a(str, str, return -1);
3626                 g_strstrip(str);
3627                 if (*str != '\0') {
3628                         compose_convert_header(buf, sizeof(buf), str,
3629                                                strlen("Subject: "));
3630                         fprintf(fp, "Subject: %s\n", buf);
3631                 }
3632         }
3633
3634         /* Message-ID */
3635         if (compose->account->gen_msgid) {
3636                 compose_generate_msgid(compose, buf, sizeof(buf));
3637                 fprintf(fp, "Message-Id: <%s>\n", buf);
3638                 compose->msgid = g_strdup(buf);
3639         }
3640
3641         /* In-Reply-To */
3642         if (compose->inreplyto && compose->to_list)
3643                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
3644
3645         /* References */
3646         if (compose->references)
3647                 fprintf(fp, "References: %s\n", compose->references);
3648
3649         /* Followup-To */
3650         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
3651 #if 0 /* NEW COMPOSE GUI */
3652         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
3653                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
3654                 if (*str != '\0') {
3655                         Xstrdup_a(str, str, return -1);
3656                         g_strstrip(str);
3657                         remove_space(str);
3658                         if (*str != '\0') {
3659                                 compose_convert_header(buf, sizeof(buf), str,
3660                                                        strlen("Followup-To: "));
3661                                 fprintf(fp, "Followup-To: %s\n", buf);
3662                         }
3663                 }
3664         }
3665 #endif
3666         /* Reply-To */
3667         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
3668 #if 0 /* NEW COMPOSE GUI */
3669         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
3670                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
3671                 if (*str != '\0') {
3672                         Xstrdup_a(str, str, return -1);
3673                         g_strstrip(str);
3674                         if (*str != '\0') {
3675                                 compose_convert_header(buf, sizeof(buf), str,
3676                                                        strlen("Reply-To: "));
3677                                 fprintf(fp, "Reply-To: %s\n", buf);
3678                         }
3679                 }
3680         }
3681 #endif
3682         /* Organization */
3683         if (compose->account->organization &&
3684             !IS_IN_CUSTOM_HEADER("Organization")) {
3685                 compose_convert_header(buf, sizeof(buf),
3686                                        compose->account->organization,
3687                                        strlen("Organization: "));
3688                 fprintf(fp, "Organization: %s\n", buf);
3689         }
3690
3691         /* Program version and system info */
3692         /* uname(&utsbuf); */
3693         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
3694                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
3695                         prog_version,
3696                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3697                         HOST_ALIAS);
3698                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3699         }
3700         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
3701                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
3702                         prog_version,
3703                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3704                         HOST_ALIAS);
3705                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3706         }
3707
3708         /* custom headers */
3709         if (compose->account->add_customhdr) {
3710                 GSList *cur;
3711
3712                 for (cur = compose->account->customhdr_list; cur != NULL;
3713                      cur = cur->next) {
3714                         CustomHeader *chdr = (CustomHeader *)cur->data;
3715
3716                         if (strcasecmp(chdr->name, "Date")         != 0 &&
3717                             strcasecmp(chdr->name, "From")         != 0 &&
3718                             strcasecmp(chdr->name, "To")           != 0 &&
3719                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
3720                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
3721                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
3722                             strcasecmp(chdr->name, "References")   != 0 &&
3723                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
3724                             strcasecmp(chdr->name, "Content-Type") != 0 &&
3725                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
3726                             != 0) {
3727                                 compose_convert_header
3728                                         (buf, sizeof(buf),
3729                                          chdr->value ? chdr->value : "",
3730                                          strlen(chdr->name) + 2);
3731                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
3732                         }
3733                 }
3734         }
3735
3736         /* MIME */
3737         fprintf(fp, "Mime-Version: 1.0\n");
3738         if (compose_use_attach(compose)) {
3739                 get_rfc822_date(buf, sizeof(buf));
3740                 subst_char(buf, ' ', '_');
3741                 subst_char(buf, ',', '_');
3742                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
3743                                                     buf, (guint)compose);
3744                 fprintf(fp,
3745                         "Content-Type: multipart/mixed;\n"
3746                         " boundary=\"%s\"\n", compose->boundary);
3747         } else {
3748                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
3749                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3750                         procmime_get_encoding_str(encoding));
3751         }
3752
3753         /* Request Return Receipt */
3754         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
3755                 if (compose->return_receipt) {
3756                         if (compose->account->name
3757                             && *compose->account->name) {
3758                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
3759                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
3760                         } else
3761                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
3762                 }
3763         }
3764
3765         /* separator between header and body */
3766         fputs("\n", fp);
3767
3768         return 0;
3769 }
3770
3771 #undef IS_IN_CUSTOM_HEADER
3772
3773 static void compose_convert_header(gchar *dest, gint len, gchar *src,
3774                                    gint header_len)