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