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