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