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