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