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