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