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