af899870255e906c2dad99a18d7f41697e00c86f
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2005 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 <glib/gi18n.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gtk/gtkmain.h>
30 #include <gtk/gtkmenu.h>
31 #include <gtk/gtkmenuitem.h>
32 #include <gtk/gtkitemfactory.h>
33 #include <gtk/gtkcheckmenuitem.h>
34 #include <gtk/gtkoptionmenu.h>
35 #include <gtk/gtkwidget.h>
36 #include <gtk/gtkvpaned.h>
37 #include <gtk/gtkentry.h>
38 #include <gtk/gtkeditable.h>
39 #include <gtk/gtkwindow.h>
40 #include <gtk/gtksignal.h>
41 #include <gtk/gtkvbox.h>
42 #include <gtk/gtkcontainer.h>
43 #include <gtk/gtkhandlebox.h>
44 #include <gtk/gtktoolbar.h>
45 #include <gtk/gtktable.h>
46 #include <gtk/gtkhbox.h>
47 #include <gtk/gtklabel.h>
48 #include <gtk/gtkscrolledwindow.h>
49 #include <gtk/gtktreeview.h>
50 #include <gtk/gtkliststore.h>
51 #include <gtk/gtktreeselection.h>
52 #include <gtk/gtktreemodel.h>
53
54 #include <gtk/gtkdnd.h>
55 #include <gtk/gtkclipboard.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <ctype.h>
60 #include <sys/types.h>
61 #include <sys/stat.h>
62 #include <unistd.h>
63 #include <time.h>
64 /* #include <sys/utsname.h> */
65 #include <stdlib.h>
66 #include <sys/wait.h>
67 #include <signal.h>
68 #include <errno.h>
69 #include <libgen.h>
70
71 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
72 #  include <wchar.h>
73 #  include <wctype.h>
74 #endif
75
76 #include "main.h"
77 #include "mainwindow.h"
78 #include "compose.h"
79 #include "addressbook.h"
80 #include "folderview.h"
81 #include "procmsg.h"
82 #include "menu.h"
83 #include "stock_pixmap.h"
84 #include "send_message.h"
85 #include "imap.h"
86 #include "news.h"
87 #include "customheader.h"
88 #include "prefs_common.h"
89 #include "prefs_account.h"
90 #include "action.h"
91 #include "account.h"
92 #include "filesel.h"
93 #include "procheader.h"
94 #include "procmime.h"
95 #include "statusbar.h"
96 #include "about.h"
97 #include "base64.h"
98 #include "quoted-printable.h"
99 #include "codeconv.h"
100 #include "utils.h"
101 #include "gtkutils.h"
102 #include "socket.h"
103 #include "alertpanel.h"
104 #include "manage_window.h"
105 #include "gtkshruler.h"
106 #include "folder.h"
107 #include "addr_compl.h"
108 #include "quote_fmt.h"
109 #include "template.h"
110 #include "undo.h"
111 #include "foldersel.h"
112 #include "toolbar.h"
113
114 enum
115 {
116         COL_MIMETYPE = 0,
117         COL_SIZE     = 1,
118         COL_NAME     = 2,
119         COL_DATA     = 3,
120         COL_AUTODATA = 4,
121         N_COL_COLUMNS
122 };
123
124 #define N_ATTACH_COLS   (N_COL_COLUMNS)
125
126 typedef enum
127 {
128         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
129         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
130         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
131         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
132         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
133         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
134         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
135         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
136         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
137         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
138         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
139         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
140         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
141         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
142         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END
143 } ComposeCallAdvancedAction;
144
145 typedef enum
146 {
147         PRIORITY_HIGHEST = 1,
148         PRIORITY_HIGH,
149         PRIORITY_NORMAL,
150         PRIORITY_LOW,
151         PRIORITY_LOWEST
152 } PriorityLevel;
153
154 typedef enum
155 {
156         COMPOSE_INSERT_SUCCESS,
157         COMPOSE_INSERT_READ_ERROR,
158         COMPOSE_INSERT_INVALID_CHARACTER,
159         COMPOSE_INSERT_NO_FILE
160 } ComposeInsertResult;
161
162 typedef enum
163 {
164         COMPOSE_QUIT_EDITING,
165         COMPOSE_KEEP_EDITING,
166         COMPOSE_AUTO_SAVE
167 } ComposeDraftAction;
168
169 typedef enum
170 {
171         COMPOSE_WRITE_FOR_SEND,
172         COMPOSE_WRITE_FOR_STORE
173 } ComposeWriteType;
174
175 #define B64_LINE_SIZE           57
176 #define B64_BUFFSIZE            77
177
178 #define MAX_REFERENCES_LEN      999
179
180 static GdkColor quote_color = {0, 0, 0, 0xbfff};
181
182 static GList *compose_list = NULL;
183
184 Compose *compose_generic_new                    (PrefsAccount   *account,
185                                                  const gchar    *to,
186                                                  FolderItem     *item,
187                                                  GPtrArray      *attach_files,
188                                                  GList          *listAddress );
189
190 static Compose *compose_create                  (PrefsAccount   *account,
191                                                  ComposeMode     mode);
192
193 static GtkWidget *compose_account_option_menu_create
194                                                 (Compose        *compose);
195 static void compose_set_template_menu           (Compose        *compose);
196 static void compose_template_apply              (Compose        *compose,
197                                                  Template       *tmpl,
198                                                  gboolean        replace);
199 static void compose_destroy                     (Compose        *compose);
200
201 static void compose_entries_set                 (Compose        *compose,
202                                                  const gchar    *mailto);
203 static gint compose_parse_header                (Compose        *compose,
204                                                  MsgInfo        *msginfo);
205 static gchar *compose_parse_references          (const gchar    *ref,
206                                                  const gchar    *msgid);
207
208 static gchar *compose_quote_fmt                 (Compose        *compose,
209                                                  MsgInfo        *msginfo,
210                                                  const gchar    *fmt,
211                                                  const gchar    *qmark,
212                                                  const gchar    *body);
213
214 static void compose_reply_set_entry             (Compose        *compose,
215                                                  MsgInfo        *msginfo,
216                                                  gboolean        to_all,
217                                                  gboolean        to_ml,
218                                                  gboolean        to_sender,
219                                                  gboolean
220                                                  followup_and_reply_to);
221 static void compose_reedit_set_entry            (Compose        *compose,
222                                                  MsgInfo        *msginfo);
223 static void compose_insert_sig                  (Compose        *compose,
224                                                  gboolean        replace);
225 static gchar *compose_get_signature_str         (Compose        *compose);
226 static ComposeInsertResult compose_insert_file  (Compose        *compose,
227                                                  const gchar    *file);
228 static void compose_attach_append               (Compose        *compose,
229                                                  const gchar    *file,
230                                                  const gchar    *type,
231                                                  const gchar    *content_type);
232 static void compose_attach_parts                (Compose        *compose,
233                                                  MsgInfo        *msginfo);
234 static void compose_wrap_line                   (Compose        *compose);
235 static void compose_wrap_line_all               (Compose        *compose);
236 static void compose_wrap_line_all_full          (Compose        *compose,
237                                                  gboolean        autowrap);
238 static void compose_set_title                   (Compose        *compose);
239 static void compose_select_account              (Compose        *compose,
240                                                  PrefsAccount   *account,
241                                                  gboolean        init);
242
243 static PrefsAccount *compose_current_mail_account(void);
244 /* static gint compose_send                     (Compose        *compose); */
245 static gboolean compose_check_for_valid_recipient
246                                                 (Compose        *compose);
247 static gboolean compose_check_entries           (Compose        *compose,
248                                                  gboolean       check_subject);
249 static gint compose_write_to_file               (Compose        *compose,
250                                                  FILE           *fp,
251                                                  gint            action);
252 static gint compose_write_body_to_file          (Compose        *compose,
253                                                  const gchar    *file);
254 static gint compose_remove_reedit_target        (Compose        *compose);
255 void compose_remove_draft                       (Compose        *compose);
256 static gint compose_queue                       (Compose        *compose,
257                                                  gint           *msgnum,
258                                                  FolderItem     **item);
259 static gint compose_queue_sub                   (Compose        *compose,
260                                                  gint           *msgnum,
261                                                  FolderItem     **item,
262                                                  gboolean       check_subject);
263 static void compose_add_attachments             (Compose        *compose,
264                                                  MimeInfo       *parent);
265 static gchar *compose_get_header                (Compose        *compose);
266
267 static void compose_convert_header              (gchar          *dest,
268                                                  gint            len,
269                                                  gchar          *src,
270                                                  gint            header_len,
271                                                  gboolean        addr_field);
272
273 static void compose_attach_info_free            (AttachInfo     *ainfo);
274 static void compose_attach_remove_selected      (Compose        *compose);
275
276 static void compose_attach_property             (Compose        *compose);
277 static void compose_attach_property_create      (gboolean       *cancelled);
278 static void attach_property_ok                  (GtkWidget      *widget,
279                                                  gboolean       *cancelled);
280 static void attach_property_cancel              (GtkWidget      *widget,
281                                                  gboolean       *cancelled);
282 static gint attach_property_delete_event        (GtkWidget      *widget,
283                                                  GdkEventAny    *event,
284                                                  gboolean       *cancelled);
285 static gboolean attach_property_key_pressed     (GtkWidget      *widget,
286                                                  GdkEventKey    *event,
287                                                  gboolean       *cancelled);
288
289 static void compose_exec_ext_editor             (Compose           *compose);
290 static gint compose_exec_ext_editor_real        (const gchar       *file);
291 static gboolean compose_ext_editor_kill         (Compose           *compose);
292 static void compose_input_cb                    (gpointer           data,
293                                                  gint               source,
294                                                  GdkInputCondition  condition);
295 static void compose_set_ext_editor_sensitive    (Compose           *compose,
296                                                  gboolean           sensitive);
297
298 static void compose_undo_state_changed          (UndoMain       *undostruct,
299                                                  gint            undo_state,
300                                                  gint            redo_state,
301                                                  gpointer        data);
302
303 static gint calc_cursor_xpos    (GtkTextView    *text,
304                                  gint            extra,
305                                  gint            char_width);
306
307 static void compose_create_header_entry (Compose *compose);
308 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
309 static void compose_update_priority_menu_item(Compose * compose);
310
311 static void compose_add_field_list      ( Compose *compose,
312                                           GList *listAddress );
313
314 /* callback functions */
315
316 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
317                                          GtkAllocation  *allocation,
318                                          GtkSHRuler     *shruler);
319 static void account_activated           (GtkMenuItem    *menuitem,
320                                          gpointer        data);
321 static void attach_selected             (GtkTreeView    *tree_view, 
322                                          GtkTreePath    *tree_path,
323                                          GtkTreeViewColumn *column, 
324                                          Compose *compose);
325 static gboolean attach_button_pressed   (GtkWidget      *widget,
326                                          GdkEventButton *event,
327                                          gpointer        data);
328 static gboolean attach_key_pressed      (GtkWidget      *widget,
329                                          GdkEventKey    *event,
330                                          gpointer        data);
331
332 static void compose_send_cb             (gpointer        data,
333                                          guint           action,
334                                          GtkWidget      *widget);
335 static void compose_send_later_cb       (gpointer        data,
336                                          guint           action,
337                                          GtkWidget      *widget);
338
339 static void compose_draft_cb            (gpointer        data,
340                                          guint           action,
341                                          GtkWidget      *widget);
342
343 static void compose_attach_cb           (gpointer        data,
344                                          guint           action,
345                                          GtkWidget      *widget);
346 static void compose_insert_file_cb      (gpointer        data,
347                                          guint           action,
348                                          GtkWidget      *widget);
349 static void compose_insert_sig_cb       (gpointer        data,
350                                          guint           action,
351                                          GtkWidget      *widget);
352
353 static void compose_close_cb            (gpointer        data,
354                                          guint           action,
355                                          GtkWidget      *widget);
356
357 static void compose_address_cb          (gpointer        data,
358                                          guint           action,
359                                          GtkWidget      *widget);
360 static void compose_template_activate_cb(GtkWidget      *widget,
361                                          gpointer        data);
362
363 static void compose_ext_editor_cb       (gpointer        data,
364                                          guint           action,
365                                          GtkWidget      *widget);
366
367 static gint compose_delete_cb           (GtkWidget      *widget,
368                                          GdkEventAny    *event,
369                                          gpointer        data);
370 static void compose_destroy_cb          (GtkWidget      *widget,
371                                          Compose        *compose);
372
373 static void compose_undo_cb             (Compose        *compose);
374 static void compose_redo_cb             (Compose        *compose);
375 static void compose_cut_cb              (Compose        *compose);
376 static void compose_copy_cb             (Compose        *compose);
377 static void compose_paste_cb            (Compose        *compose);
378 static void compose_paste_as_quote_cb   (Compose        *compose);
379 static void compose_allsel_cb           (Compose        *compose);
380
381 static void compose_advanced_action_cb  (Compose                   *compose,
382                                          ComposeCallAdvancedAction  action);
383
384 static void compose_grab_focus_cb       (GtkWidget      *widget,
385                                          Compose        *compose);
386 static void compose_grab_focus_before_cb(GtkWidget      *widget,
387                                          Compose        *compose);
388
389 static void compose_changed_cb          (GtkTextBuffer  *textbuf,
390                                          Compose        *compose);
391
392 static void compose_toggle_autowrap_cb  (gpointer        data,
393                                          guint           action,
394                                          GtkWidget      *widget);
395
396 #if 0
397 static void compose_toggle_to_cb        (gpointer        data,
398                                          guint           action,
399                                          GtkWidget      *widget);
400 static void compose_toggle_cc_cb        (gpointer        data,
401                                          guint           action,
402                                          GtkWidget      *widget);
403 static void compose_toggle_bcc_cb       (gpointer        data,
404                                          guint           action,
405                                          GtkWidget      *widget);
406 static void compose_toggle_replyto_cb   (gpointer        data,
407                                          guint           action,
408                                          GtkWidget      *widget);
409 static void compose_toggle_followupto_cb(gpointer        data,
410                                          guint           action,
411                                          GtkWidget      *widget);
412 static void compose_toggle_attach_cb    (gpointer        data,
413                                          guint           action,
414                                          GtkWidget      *widget);
415 #endif
416 static void compose_toggle_ruler_cb     (gpointer        data,
417                                          guint           action,
418                                          GtkWidget      *widget);
419 static void compose_toggle_sign_cb      (gpointer        data,
420                                          guint           action,
421                                          GtkWidget      *widget);
422 static void compose_toggle_encrypt_cb   (gpointer        data,
423                                          guint           action,
424                                          GtkWidget      *widget);
425 static void compose_set_privacy_system_cb(GtkWidget      *widget,
426                                           gpointer        data);
427 static void compose_update_privacy_system_menu_item(Compose * compose);
428 static void activate_privacy_system     (Compose *compose, 
429                                          PrefsAccount *account);
430 static void compose_use_signing(Compose *compose, gboolean use_signing);
431 static void compose_use_encryption(Compose *compose, gboolean use_encryption);
432 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
433                                              GtkWidget *widget);
434 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
435                                              GtkWidget *widget);
436 static void compose_set_priority_cb     (gpointer        data,
437                                          guint           action,
438                                          GtkWidget      *widget);
439
440 static void compose_attach_drag_received_cb (GtkWidget          *widget,
441                                              GdkDragContext     *drag_context,
442                                              gint                x,
443                                              gint                y,
444                                              GtkSelectionData   *data,
445                                              guint               info,
446                                              guint               time,
447                                              gpointer            user_data);
448 static void compose_insert_drag_received_cb (GtkWidget          *widget,
449                                              GdkDragContext     *drag_context,
450                                              gint                x,
451                                              gint                y,
452                                              GtkSelectionData   *data,
453                                              guint               info,
454                                              guint               time,
455                                              gpointer            user_data);
456 static void compose_header_drag_received_cb (GtkWidget          *widget,
457                                              GdkDragContext     *drag_context,
458                                              gint                x,
459                                              gint                y,
460                                              GtkSelectionData   *data,
461                                              guint               info,
462                                              guint               time,
463                                              gpointer            user_data);
464
465 static gboolean compose_drag_drop           (GtkWidget *widget,
466                                              GdkDragContext *drag_context,
467                                              gint x, gint y,
468                                              guint time, gpointer user_data);
469 #if 0
470 static void to_activated                (GtkWidget      *widget,
471                                          Compose        *compose);
472 static void newsgroups_activated        (GtkWidget      *widget,
473                                          Compose        *compose);
474 static void cc_activated                (GtkWidget      *widget,
475                                          Compose        *compose);
476 static void bcc_activated               (GtkWidget      *widget,
477                                          Compose        *compose);
478 static void replyto_activated           (GtkWidget      *widget,
479                                          Compose        *compose);
480 static void followupto_activated        (GtkWidget      *widget,
481                                          Compose        *compose);
482 static void subject_activated           (GtkWidget      *widget,
483                                          Compose        *compose);
484 #endif
485
486 static void text_inserted               (GtkTextBuffer  *buffer,
487                                          GtkTextIter    *iter,
488                                          const gchar    *text,
489                                          gint            len,
490                                          Compose        *compose);
491 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
492                                   gboolean to_all, gboolean to_ml,
493                                   gboolean to_sender,
494                                   gboolean followup_and_reply_to,
495                                   const gchar *body);
496
497 gboolean compose_headerentry_changed_cb    (GtkWidget          *entry,
498                                             ComposeHeaderEntry *headerentry);
499 gboolean compose_headerentry_key_press_event_cb(GtkWidget              *entry,
500                                             GdkEventKey        *event,
501                                             ComposeHeaderEntry *headerentry);
502
503 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
504
505 static void compose_allow_user_actions (Compose *compose, gboolean allow);
506
507 #if USE_ASPELL
508 static void compose_check_all              (Compose *compose);
509 static void compose_highlight_all          (Compose *compose);
510 static void compose_check_backwards        (Compose *compose);
511 static void compose_check_forwards_go      (Compose *compose);
512 #endif
513
514 static gint compose_defer_auto_save_draft       (Compose        *compose);
515 static PrefsAccount *compose_guess_forward_account_from_msginfo (MsgInfo *msginfo);
516
517 static void compose_close       (Compose *compose);
518
519 static GtkItemFactoryEntry compose_popup_entries[] =
520 {
521         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
522         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
523         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
524         {N_("/_Properties..."), NULL, compose_attach_property, 0, NULL}
525 };
526
527 static GtkItemFactoryEntry compose_entries[] =
528 {
529         {N_("/_Message"),                               NULL, NULL, 0, "<Branch>"},
530         {N_("/_Message/_Send"),         "<control>Return",
531                                         compose_send_cb, 0, NULL},
532         {N_("/_Message/Send _later"),   "<shift><control>S",
533                                         compose_send_later_cb,  0, NULL},
534         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
535         {N_("/_Message/_Attach file"),          "<control>M", compose_attach_cb,      0, NULL},
536         {N_("/_Message/_Insert file"),          "<control>I", compose_insert_file_cb, 0, NULL},
537         {N_("/_Message/Insert si_gnature"),     "<control>G", compose_insert_sig_cb,  0, NULL},
538         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
539         {N_("/_Message/_Save"),
540                                                 "<control>S", compose_draft_cb, COMPOSE_KEEP_EDITING, NULL},
541         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
542         {N_("/_Message/_Close"),                        "<control>W", compose_close_cb, 0, NULL},
543
544         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
545         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
546         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
547         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
548         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
549         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
550         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
551         {N_("/_Edit/Paste as _quotation"),
552                                         NULL, compose_paste_as_quote_cb, 0, NULL},
553         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
554         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
555         {N_("/_Edit/A_dvanced/Move a character backward"),
556                                         "<control>B",
557                                         compose_advanced_action_cb,
558                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
559                                         NULL},
560         {N_("/_Edit/A_dvanced/Move a character forward"),
561                                         "<control>F",
562                                         compose_advanced_action_cb,
563                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
564                                         NULL},
565         {N_("/_Edit/A_dvanced/Move a word backward"),
566                                         NULL, /* "<alt>B" */
567                                         compose_advanced_action_cb,
568                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
569                                         NULL},
570         {N_("/_Edit/A_dvanced/Move a word forward"),
571                                         NULL, /* "<alt>F" */
572                                         compose_advanced_action_cb,
573                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
574                                         NULL},
575         {N_("/_Edit/A_dvanced/Move to beginning of line"),
576                                         NULL, /* "<control>A" */
577                                         compose_advanced_action_cb,
578                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
579                                         NULL},
580         {N_("/_Edit/A_dvanced/Move to end of line"),
581                                         "<control>E",
582                                         compose_advanced_action_cb,
583                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
584                                         NULL},
585         {N_("/_Edit/A_dvanced/Move to previous line"),
586                                         "<control>P",
587                                         compose_advanced_action_cb,
588                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
589                                         NULL},
590         {N_("/_Edit/A_dvanced/Move to next line"),
591                                         "<control>N",
592                                         compose_advanced_action_cb,
593                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
594                                         NULL},
595         {N_("/_Edit/A_dvanced/Delete a character backward"),
596                                         "<control>H",
597                                         compose_advanced_action_cb,
598                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
599                                         NULL},
600         {N_("/_Edit/A_dvanced/Delete a character forward"),
601                                         "<control>D",
602                                         compose_advanced_action_cb,
603                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
604                                         NULL},
605         {N_("/_Edit/A_dvanced/Delete a word backward"),
606                                         NULL, /* "<control>W" */
607                                         compose_advanced_action_cb,
608                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
609                                         NULL},
610         {N_("/_Edit/A_dvanced/Delete a word forward"),
611                                         NULL, /* "<alt>D", */
612                                         compose_advanced_action_cb,
613                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
614                                         NULL},
615         {N_("/_Edit/A_dvanced/Delete line"),
616                                         "<control>U",
617                                         compose_advanced_action_cb,
618                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
619                                         NULL},
620         {N_("/_Edit/A_dvanced/Delete entire line"),
621                                         NULL,
622                                         compose_advanced_action_cb,
623                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
624                                         NULL},
625         {N_("/_Edit/A_dvanced/Delete to end of line"),
626                                         "<control>K",
627                                         compose_advanced_action_cb,
628                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END,
629                                         NULL},
630         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
631         {N_("/_Edit/_Wrap current paragraph"),
632                                         "<control>L", compose_wrap_line, 0, NULL},
633         {N_("/_Edit/Wrap all long _lines"),
634                                         "<control><alt>L", compose_wrap_line_all, 0, NULL},
635         {N_("/_Edit/Aut_o wrapping"),   "<shift><control>L", compose_toggle_autowrap_cb, 0, "<ToggleItem>"},
636         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
637         {N_("/_Edit/Edit with e_xternal editor"),
638                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
639 #if USE_ASPELL
640         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
641         {N_("/_Spelling/_Check all or check selection"),
642                                         NULL, compose_check_all, 0, NULL},
643         {N_("/_Spelling/_Highlight all misspelled words"),
644                                         NULL, compose_highlight_all, 0, NULL},
645         {N_("/_Spelling/Check _backwards misspelled word"),
646                                         NULL, compose_check_backwards , 0, NULL},
647         {N_("/_Spelling/_Forward to next misspelled word"),
648                                         NULL, compose_check_forwards_go, 0, NULL},
649         {N_("/_Spelling/---"),          NULL, NULL, 0, "<Separator>"},
650         {N_("/_Spelling/_Spelling Configuration"),
651                                         NULL, NULL, 0, "<Branch>"},
652 #endif
653         {N_("/_Options"),               NULL, NULL, 0, "<Branch>"},
654         {N_("/_Options/Privacy System"),                NULL, NULL,   0, "<Branch>"},
655         {N_("/_Options/Privacy System/None"),   NULL, NULL,   0, "<RadioItem>"},
656         {N_("/_Options/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
657         {N_("/_Options/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
658         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
659         {N_("/_Options/_Priority"),     NULL,           NULL,   0, "<Branch>"},
660         {N_("/_Options/Priority/_Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
661         {N_("/_Options/Priority/Hi_gh"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Options/Priority/Highest"},
662         {N_("/_Options/Priority/_Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Options/Priority/Highest"},
663         {N_("/_Options/Priority/Lo_w"),    NULL, compose_set_priority_cb, PRIORITY_LOW, "/Options/Priority/Highest"},
664         {N_("/_Options/Priority/_Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Options/Priority/Highest"},
665         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
666         {N_("/_Options/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
667         {N_("/_Options/Remo_ve references"),    NULL, compose_toggle_remove_refs_cb, 0, "<ToggleItem>"},
668         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
669         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
670         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
671         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
672         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
673         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
674         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
675 };
676
677 static GtkTargetEntry compose_mime_types[] =
678 {
679         {"text/uri-list", 0, 0},
680         {"text/plain", 0, 0},
681         {"STRING", 0, 0}
682 };
683
684 static gboolean compose_put_existing_to_front(MsgInfo *info)
685 {
686         GList *compose_list = compose_get_compose_list();
687         GList *elem = NULL;
688         
689         if (compose_list) {
690                 for (elem = compose_list; elem != NULL && elem->data != NULL; 
691                      elem = elem->next) {
692                         Compose *c = (Compose*)elem->data;
693
694                         if (!c->targetinfo || !c->targetinfo->msgid ||
695                             !info->msgid)
696                                 continue;
697
698                         if (!strcmp(c->targetinfo->msgid, info->msgid)) {
699                                 gtkut_window_popup(c->window);
700                                 return TRUE;
701                         }
702                 }
703         }
704         return FALSE;
705 }
706
707 Compose *compose_new(PrefsAccount *account, const gchar *mailto,
708                      GPtrArray *attach_files)
709 {
710         return compose_generic_new(account, mailto, NULL, attach_files, NULL);
711 }
712
713 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
714 {
715         return compose_generic_new(account, NULL, item, NULL, NULL);
716 }
717
718 Compose *compose_new_with_list( PrefsAccount *account, GList *listAddress )
719 {
720         return compose_generic_new( account, NULL, NULL, NULL, listAddress );
721 }
722
723 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item,
724                              GPtrArray *attach_files, GList *listAddress )
725 {
726         Compose *compose;
727         GtkTextView *textview;
728         GtkTextBuffer *textbuf;
729         GtkTextIter iter;
730         GtkItemFactory *ifactory;
731
732         if (item && item->prefs && item->prefs->enable_default_account)
733                 account = account_find_from_id(item->prefs->default_account);
734
735         if (!account) account = cur_account;
736         g_return_val_if_fail(account != NULL, NULL);
737
738         compose = compose_create(account, COMPOSE_NEW);
739         ifactory = gtk_item_factory_from_widget(compose->menubar);
740
741         compose->replyinfo = NULL;
742         compose->fwdinfo   = NULL;
743
744         textview = GTK_TEXT_VIEW(compose->text);
745         textbuf = gtk_text_view_get_buffer(textview);
746
747         undo_block(compose->undostruct);
748 #ifdef USE_ASPELL
749         if (item && item->prefs && item->prefs->enable_default_dictionary &&
750             compose->gtkaspell) 
751                 gtkaspell_change_dict(compose->gtkaspell, 
752                     item->prefs->default_dictionary);
753 #endif
754
755         if (account->auto_sig)
756                 compose_insert_sig(compose, FALSE);
757         gtk_text_buffer_get_start_iter(textbuf, &iter);
758         gtk_text_buffer_place_cursor(textbuf, &iter);
759
760         if (account->protocol != A_NNTP) {
761                 if (mailto && *mailto != '\0') {
762                         compose_entries_set(compose, mailto);
763
764                 } else if (item && item->prefs->enable_default_to) {
765                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
766                         compose_entry_mark_default_to(compose, item->prefs->default_to);
767                 }
768                 if (item && item->ret_rcpt) {
769                         menu_set_active(ifactory, "/Message/Request Return Receipt", TRUE);
770                 }
771         } else {
772                 if (mailto) {
773                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
774                 }
775                 /*
776                  * CLAWS: just don't allow return receipt request, even if the user
777                  * may want to send an email. simple but foolproof.
778                  */
779                 menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE); 
780         }
781         compose_add_field_list( compose, listAddress );
782
783         if (attach_files) {
784                 gint i;
785                 gchar *file;
786
787                 for (i = 0; i < attach_files->len; i++) {
788                         file = g_ptr_array_index(attach_files, i);
789                         compose_attach_append(compose, file, file, NULL);
790                 }
791         }
792
793         compose_show_first_last_header(compose, TRUE);
794
795         /* Set save folder */
796         if (item && item->prefs && item->prefs->save_copy_to_folder) {
797                 gchar *folderidentifier;
798
799                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
800                 folderidentifier = folder_item_get_identifier(item);
801                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
802                 g_free(folderidentifier);
803         }
804         
805         gtk_widget_grab_focus(compose->header_last->entry);
806
807         undo_unblock(compose->undostruct);
808
809         if (prefs_common.auto_exteditor)
810                 compose_exec_ext_editor(compose);
811
812         return compose;
813 }
814
815 /*
816 Compose *compose_new_followup_and_replyto(PrefsAccount *account,
817                                            const gchar *followupto, gchar * to)
818 {
819         Compose *compose;
820
821         if (!account) account = cur_account;
822         g_return_val_if_fail(account != NULL, NULL);
823         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
824
825         compose = compose_create(account, COMPOSE_NEW);
826
827         if (prefs_common.auto_sig)
828                 compose_insert_sig(compose);
829         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
830         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
831
832         compose_entry_append(compose, to, COMPOSE_TO);
833         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
834         gtk_widget_grab_focus(compose->subject_entry);
835
836         return compose;
837 }
838 */
839
840 void compose_reply_mode(ComposeMode mode, GSList *msginfo_list, gchar *body)
841 {
842         MsgInfo *msginfo;
843         guint list_len;
844
845         g_return_if_fail(msginfo_list != NULL);
846
847         msginfo = (MsgInfo*)g_slist_nth_data(msginfo_list, 0);
848         g_return_if_fail(msginfo != NULL);
849
850         list_len = g_slist_length(msginfo_list);
851
852         switch (mode) {
853         case COMPOSE_REPLY:
854                 compose_reply(msginfo, prefs_common.reply_with_quote,
855                               FALSE, prefs_common.default_reply_list, FALSE, body);
856                 break;
857         case COMPOSE_REPLY_WITH_QUOTE:
858                 compose_reply(msginfo, TRUE, FALSE, prefs_common.default_reply_list, FALSE, body);
859                 break;
860         case COMPOSE_REPLY_WITHOUT_QUOTE:
861                 compose_reply(msginfo, FALSE, FALSE, prefs_common.default_reply_list, FALSE, NULL);
862                 break;
863         case COMPOSE_REPLY_TO_SENDER:
864                 compose_reply(msginfo, prefs_common.reply_with_quote,
865                               FALSE, FALSE, TRUE, body);
866                 break;
867         case COMPOSE_FOLLOWUP_AND_REPLY_TO:
868                 compose_followup_and_reply_to(msginfo,
869                                               prefs_common.reply_with_quote,
870                                               FALSE, FALSE, body);
871                 break;
872         case COMPOSE_REPLY_TO_SENDER_WITH_QUOTE:
873                 compose_reply(msginfo, TRUE, FALSE, FALSE, TRUE, body);
874                 break;
875         case COMPOSE_REPLY_TO_SENDER_WITHOUT_QUOTE:
876                 compose_reply(msginfo, FALSE, FALSE, FALSE, TRUE, NULL);
877                 break;
878         case COMPOSE_REPLY_TO_ALL:
879                 compose_reply(msginfo, prefs_common.reply_with_quote,
880                               TRUE, FALSE, FALSE, body);
881                 break;
882         case COMPOSE_REPLY_TO_ALL_WITH_QUOTE:
883                 compose_reply(msginfo, TRUE, TRUE, FALSE, FALSE, body);
884                 break;
885         case COMPOSE_REPLY_TO_ALL_WITHOUT_QUOTE:
886                 compose_reply(msginfo, FALSE, TRUE, FALSE, FALSE, NULL);
887                 break;
888         case COMPOSE_REPLY_TO_LIST:
889                 compose_reply(msginfo, prefs_common.reply_with_quote,
890                               FALSE, TRUE, FALSE, body);
891                 break;
892         case COMPOSE_REPLY_TO_LIST_WITH_QUOTE:
893                 compose_reply(msginfo, TRUE, FALSE, TRUE, FALSE, body);
894                 break;
895         case COMPOSE_REPLY_TO_LIST_WITHOUT_QUOTE:
896                 compose_reply(msginfo, FALSE, FALSE, TRUE, FALSE, NULL);
897                 break;
898         case COMPOSE_FORWARD:
899                 if (prefs_common.forward_as_attachment) {
900                         compose_reply_mode(COMPOSE_FORWARD_AS_ATTACH, msginfo_list, body);
901                         return;
902                 } else {
903                         compose_reply_mode(COMPOSE_FORWARD_INLINE, msginfo_list, body);
904                         return;
905                 }
906                 break;
907         case COMPOSE_FORWARD_INLINE:
908                 /* check if we reply to more than one Message */
909                 if (list_len == 1) {
910                         compose_forward(NULL, msginfo, FALSE, body, FALSE);
911                         break;
912                 } 
913                 /* more messages FALL THROUGH */
914         case COMPOSE_FORWARD_AS_ATTACH:
915                 compose_forward_multiple(NULL, msginfo_list);
916                 break;
917         case COMPOSE_REDIRECT:
918                 compose_redirect(NULL, msginfo);
919                 break;
920         default:
921                 g_warning("compose_reply(): invalid Compose Mode: %d\n", mode);
922         }
923 }
924
925 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
926                    gboolean to_ml, gboolean to_sender, 
927                    const gchar *body)
928 {
929         compose_generic_reply(msginfo, quote, to_all, to_ml, 
930                               to_sender, FALSE, body);
931 }
932
933 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
934                                    gboolean to_all,
935                                    gboolean to_sender,
936                                    const gchar *body)
937 {
938         compose_generic_reply(msginfo, quote, to_all, FALSE, 
939                               to_sender, TRUE, body);
940 }
941
942 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
943                                   gboolean to_all, gboolean to_ml,
944                                   gboolean to_sender,
945                                   gboolean followup_and_reply_to,
946                                   const gchar *body)
947 {
948         GtkItemFactory *ifactory;
949         Compose *compose;
950         PrefsAccount *account = NULL;
951         PrefsAccount *reply_account;
952         GtkTextView *textview;
953         GtkTextBuffer *textbuf;
954         GtkTextIter iter;
955         int cursor_pos;
956
957         g_return_if_fail(msginfo != NULL);
958         g_return_if_fail(msginfo->folder != NULL);
959
960         account = account_get_reply_account(msginfo, prefs_common.reply_account_autosel);
961         
962         g_return_if_fail(account != NULL);
963
964         if (to_sender && account->protocol == A_NNTP &&
965             !followup_and_reply_to) {
966                 reply_account =
967                         account_find_from_address(account->address);
968                 if (!reply_account)
969                         reply_account = compose_current_mail_account();
970                 if (!reply_account)
971                         return;
972         } else
973                 reply_account = account;
974
975         compose = compose_create(account, COMPOSE_REPLY);
976         ifactory = gtk_item_factory_from_widget(compose->menubar);
977
978         menu_set_active(ifactory, "/Options/Remove references", FALSE);
979         menu_set_sensitive(ifactory, "/Options/Remove references", TRUE);
980
981         compose->replyinfo = procmsg_msginfo_get_full_info(msginfo);
982         if (!compose->replyinfo)
983                 compose->replyinfo = procmsg_msginfo_copy(msginfo);
984
985         if (msginfo->folder && msginfo->folder->ret_rcpt)
986                 menu_set_active(ifactory, "/Message/Request Return Receipt", TRUE);
987
988         /* Set save folder */
989         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
990                 gchar *folderidentifier;
991
992                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
993                 folderidentifier = folder_item_get_identifier(msginfo->folder);
994                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
995                 g_free(folderidentifier);
996         }
997
998         if (compose_parse_header(compose, msginfo) < 0) return;
999         compose_reply_set_entry(compose, msginfo, to_all, to_ml, 
1000                                 to_sender, followup_and_reply_to);
1001         compose_show_first_last_header(compose, TRUE);
1002
1003         textview = (GTK_TEXT_VIEW(compose->text));
1004         textbuf = gtk_text_view_get_buffer(textview);
1005         
1006         undo_block(compose->undostruct);
1007 #ifdef USE_ASPELL
1008         if (msginfo->folder && msginfo->folder->prefs && 
1009             msginfo->folder->prefs && 
1010             msginfo->folder->prefs->enable_default_dictionary &&
1011             compose->gtkaspell)
1012                 gtkaspell_change_dict(compose->gtkaspell, 
1013                     msginfo->folder->prefs->default_dictionary);
1014 #endif
1015
1016         if (quote) {
1017                 gchar *qmark;
1018
1019                 if (prefs_common.quotemark && *prefs_common.quotemark)
1020                         qmark = prefs_common.quotemark;
1021                 else
1022                         qmark = "> ";
1023
1024                 compose_quote_fmt(compose, compose->replyinfo,
1025                                   prefs_common.quotefmt,
1026                                   qmark, body);
1027         }
1028
1029         if (account->auto_sig)
1030                 compose_insert_sig(compose, FALSE);
1031
1032         cursor_pos = quote_fmt_get_cursor_pos();
1033         gtk_text_buffer_get_start_iter(textbuf, &iter);
1034         gtk_text_buffer_get_iter_at_offset(textbuf, &iter, cursor_pos);
1035         gtk_text_buffer_place_cursor(textbuf, &iter);
1036         
1037         if (quote && prefs_common.linewrap_quote)
1038                 compose_wrap_line_all(compose);
1039
1040         gtk_widget_grab_focus(compose->text);
1041
1042         undo_unblock(compose->undostruct);
1043
1044         if (prefs_common.auto_exteditor)
1045                 compose_exec_ext_editor(compose);
1046 }
1047
1048 #define INSERT_FW_HEADER(var, hdr) \
1049 if (msginfo->var && *msginfo->var) { \
1050         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1051         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1052         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1053 }
1054
1055 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1056                          gboolean as_attach, const gchar *body,
1057                          gboolean no_extedit)
1058 {
1059         Compose *compose;
1060         GtkTextView *textview;
1061         GtkTextBuffer *textbuf;
1062         GtkTextIter iter;
1063
1064         g_return_val_if_fail(msginfo != NULL, NULL);
1065         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1066
1067         if (!account && 
1068             !(account = compose_guess_forward_account_from_msginfo
1069                                 (msginfo)))
1070                 account = cur_account;
1071
1072         compose = compose_create(account, COMPOSE_FORWARD);
1073
1074         compose->fwdinfo = procmsg_msginfo_get_full_info(msginfo);
1075         if (!compose->fwdinfo)
1076                 compose->fwdinfo = procmsg_msginfo_copy(msginfo);
1077
1078         if (msginfo->subject && *msginfo->subject) {
1079                 gchar *buf, *buf2, *p;
1080
1081                 buf = p = g_strdup(msginfo->subject);
1082                 p += subject_get_prefix_length(p);
1083                 memmove(buf, p, strlen(p) + 1);
1084
1085                 buf2 = g_strdup_printf("Fw: %s", buf);
1086                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1087                 
1088                 g_free(buf);
1089                 g_free(buf2);
1090         }
1091
1092         textview = GTK_TEXT_VIEW(compose->text);
1093         textbuf = gtk_text_view_get_buffer(textview);
1094
1095         if (as_attach) {
1096                 gchar *msgfile;
1097
1098                 msgfile = procmsg_get_message_file_path(msginfo);
1099                 if (!is_file_exist(msgfile))
1100                         g_warning("%s: file not exist\n", msgfile);
1101                 else
1102                         compose_attach_append(compose, msgfile, msgfile,
1103                                               "message/rfc822");
1104
1105                 g_free(msgfile);
1106         } else {
1107                 gchar *qmark;
1108                 MsgInfo *full_msginfo;
1109
1110                 full_msginfo = procmsg_msginfo_get_full_info(msginfo);
1111                 if (!full_msginfo)
1112                         full_msginfo = procmsg_msginfo_copy(msginfo);
1113
1114                 if (prefs_common.fw_quotemark &&
1115                     *prefs_common.fw_quotemark)
1116                         qmark = prefs_common.fw_quotemark;
1117                 else
1118                         qmark = "> ";
1119
1120                 compose_quote_fmt(compose, full_msginfo,
1121                                   prefs_common.fw_quotefmt,
1122                                   qmark, body);
1123                 compose_attach_parts(compose, msginfo);
1124
1125                 procmsg_msginfo_free(full_msginfo);
1126         }
1127
1128         if (account->auto_sig)
1129                 compose_insert_sig(compose, FALSE);
1130
1131         if (prefs_common.linewrap_quote)
1132                 compose_wrap_line_all(compose);
1133
1134         gtk_text_buffer_get_start_iter(textbuf, &iter);
1135         gtk_text_buffer_place_cursor(textbuf, &iter);
1136
1137 #if 0 /* NEW COMPOSE GUI */
1138         if (account->protocol != A_NNTP)
1139                 gtk_widget_grab_focus(compose->to_entry);
1140         else
1141                 gtk_widget_grab_focus(compose->newsgroups_entry);
1142 #endif
1143         gtk_widget_grab_focus(compose->header_last->entry);
1144
1145         if (!no_extedit && prefs_common.auto_exteditor)
1146                 compose_exec_ext_editor(compose);
1147         
1148         /*save folder*/
1149         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1150                 gchar *folderidentifier;
1151
1152                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1153                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1154                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1155                 g_free(folderidentifier);
1156         }
1157
1158         return compose;
1159 }
1160
1161 #undef INSERT_FW_HEADER
1162
1163 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1164 {
1165         Compose *compose;
1166         GtkTextView *textview;
1167         GtkTextBuffer *textbuf;
1168         GtkTextIter iter;
1169         GSList *msginfo;
1170         gchar *msgfile;
1171
1172         g_return_val_if_fail(msginfo_list != NULL, NULL);
1173
1174         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next)
1175                 if (((MsgInfo *)msginfo->data)->folder == NULL)
1176                         return NULL;
1177
1178         /* guess account from first selected message */
1179         if (!account && 
1180             !(account = compose_guess_forward_account_from_msginfo
1181                                 (msginfo_list->data)))
1182                 account = cur_account;
1183
1184         g_return_val_if_fail(account != NULL, NULL);
1185
1186         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1187                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1188                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1189         }
1190
1191         compose = compose_create(account, COMPOSE_FORWARD);
1192
1193         textview = GTK_TEXT_VIEW(compose->text);
1194         textbuf = gtk_text_view_get_buffer(textview);
1195
1196         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1197                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1198                 if (!is_file_exist(msgfile))
1199                         g_warning("%s: file not exist\n", msgfile);
1200                 else
1201                         compose_attach_append(compose, msgfile, msgfile,
1202                                 "message/rfc822");
1203                 g_free(msgfile);
1204         }
1205
1206         if (account->auto_sig)
1207                 compose_insert_sig(compose, FALSE);
1208
1209         if (prefs_common.linewrap_quote)
1210                 compose_wrap_line_all(compose);
1211
1212         gtk_text_buffer_get_start_iter(textbuf, &iter);
1213         gtk_text_buffer_place_cursor(textbuf, &iter);
1214
1215         gtk_widget_grab_focus(compose->header_last->entry);
1216         
1217 #if 0 /* NEW COMPOSE GUI */
1218         if (account->protocol != A_NNTP)
1219                 gtk_widget_grab_focus(compose->to_entry);
1220         else
1221                 gtk_widget_grab_focus(compose->newsgroups_entry);
1222 #endif
1223
1224         return compose;
1225 }
1226
1227 void compose_reedit(MsgInfo *msginfo)
1228 {
1229         Compose *compose;
1230         PrefsAccount *account = NULL;
1231         GtkTextView *textview;
1232         GtkTextBuffer *textbuf;
1233         GtkTextMark *mark;
1234         GtkTextIter iter;
1235         FILE *fp;
1236         gchar buf[BUFFSIZE];
1237         gboolean use_signing = FALSE;
1238         gboolean use_encryption = FALSE;
1239         gchar *privacy_system = NULL;
1240
1241         g_return_if_fail(msginfo != NULL);
1242         g_return_if_fail(msginfo->folder != NULL);
1243
1244         if (compose_put_existing_to_front(msginfo)) 
1245                 return;
1246
1247         if (msginfo->folder->stype == F_QUEUE || msginfo->folder->stype == F_DRAFT) {
1248                 gchar queueheader_buf[BUFFSIZE];
1249                 gint id, param;
1250
1251                 /* Select Account from queue headers */
1252                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1253                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1254                         id = atoi(&queueheader_buf[strlen("X-Sylpheed-Account-Id:")]);
1255                         account = account_find_from_id(id);
1256                 }
1257                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1258                                              sizeof(queueheader_buf), "NAID:")) {
1259                         id = atoi(&queueheader_buf[strlen("NAID:")]);
1260                         account = account_find_from_id(id);
1261                 }
1262                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1263                                                     sizeof(queueheader_buf), "MAID:")) {
1264                         id = atoi(&queueheader_buf[strlen("MAID:")]);
1265                         account = account_find_from_id(id);
1266                 }
1267                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1268                                                                 sizeof(queueheader_buf), "S:")) {
1269                         account = account_find_from_address(queueheader_buf);
1270                 }
1271                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1272                                              sizeof(queueheader_buf), "X-Sylpheed-Sign:")) {
1273                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Sign:")]);
1274                         use_signing = param;
1275                         
1276                 }
1277                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1278                                              sizeof(queueheader_buf), "X-Sylpheed-Encrypt:")) {
1279                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Encrypt:")]);
1280                         use_encryption = param;
1281                 }
1282                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1283                                             sizeof(queueheader_buf), "X-Sylpheed-Privacy-System:")) {
1284                         privacy_system = g_strdup(&queueheader_buf[strlen("X-Sylpheed-Privacy-System:")]);
1285                 }
1286                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1287                                              sizeof(queueheader_buf), "X-Priority: ")) {
1288                         param = atoi(&queueheader_buf[strlen("X-Priority: ")]); /* mind the space */
1289                         compose->priority = param;
1290                 }
1291         } else 
1292                 account = msginfo->folder->folder->account;
1293
1294         if (!account && prefs_common.reedit_account_autosel) {
1295                 gchar from[BUFFSIZE];
1296                 if (!procheader_get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1297                         extract_address(from);
1298                         account = account_find_from_address(from);
1299                 }
1300         }
1301         if (!account) account = cur_account;
1302         g_return_if_fail(account != NULL);
1303
1304         compose = compose_create(account, COMPOSE_REEDIT);
1305         compose->privacy_system = privacy_system;
1306         compose_use_signing(compose, use_signing);
1307         compose_use_encryption(compose, use_encryption);
1308         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1309
1310         if (msginfo->folder->stype == F_QUEUE
1311         ||  msginfo->folder->stype == F_DRAFT) {
1312                 gchar queueheader_buf[BUFFSIZE];
1313
1314                 /* Set message save folder */
1315                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1316                         gint startpos = 0;
1317
1318                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1319                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1320                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1321                 }
1322         }
1323         
1324         if (compose_parse_header(compose, msginfo) < 0) return;
1325         compose_reedit_set_entry(compose, msginfo);
1326
1327         textview = GTK_TEXT_VIEW(compose->text);
1328         textbuf = gtk_text_view_get_buffer(textview);
1329         mark = gtk_text_buffer_get_insert(textbuf);
1330         gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1331
1332         g_signal_handlers_block_by_func(G_OBJECT(textbuf),
1333                                         G_CALLBACK(compose_changed_cb),
1334                                         compose);
1335                                         
1336         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1337                 g_warning("Can't get text part\n");
1338         else {
1339                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1340                         strcrchomp(buf);
1341                         gtk_text_buffer_insert(textbuf, &iter, buf, -1);
1342                 }
1343                 fclose(fp);
1344         }
1345         
1346         compose_attach_parts(compose, msginfo);
1347
1348         g_signal_handlers_unblock_by_func(G_OBJECT(textbuf),
1349                                         G_CALLBACK(compose_changed_cb),
1350                                         compose);
1351
1352         gtk_widget_grab_focus(compose->text);
1353
1354         if (prefs_common.auto_exteditor)
1355                 compose_exec_ext_editor(compose);
1356 }
1357
1358 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
1359 {
1360         Compose *compose;
1361         gchar *filename;
1362         GtkItemFactory *ifactory;
1363         FolderItem *item;
1364
1365         g_return_val_if_fail(msginfo != NULL, NULL);
1366
1367         if (!account)
1368                 account = account_get_reply_account(msginfo,
1369                                         prefs_common.reply_account_autosel);
1370         g_return_val_if_fail(account != NULL, NULL);
1371
1372         compose = compose_create(account, COMPOSE_REDIRECT);
1373         ifactory = gtk_item_factory_from_widget(compose->menubar);
1374
1375         compose->replyinfo = NULL;
1376         compose->fwdinfo = NULL;
1377
1378         compose_show_first_last_header(compose, TRUE);
1379
1380         gtk_widget_grab_focus(compose->header_last->entry);
1381
1382         filename = procmsg_get_message_file_path(msginfo);
1383         if (filename == NULL)
1384                 return NULL;
1385
1386         compose->redirect_filename = filename;
1387         
1388         /* Set save folder */
1389         item = msginfo->folder;
1390         if (item && item->prefs && item->prefs->save_copy_to_folder) {
1391                 gchar *folderidentifier;
1392
1393                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
1394                 folderidentifier = folder_item_get_identifier(item);
1395                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1396                 g_free(folderidentifier);
1397         }
1398
1399         compose_attach_parts(compose, msginfo);
1400
1401         if (msginfo->subject)
1402                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1403                                    msginfo->subject);
1404         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1405
1406         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL);
1407         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), FALSE);
1408
1409         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1410         menu_set_sensitive(ifactory, "/Add...", FALSE);
1411         menu_set_sensitive(ifactory, "/Remove", FALSE);
1412         menu_set_sensitive(ifactory, "/Properties...", FALSE);
1413
1414         ifactory = gtk_item_factory_from_widget(compose->menubar);
1415         menu_set_sensitive(ifactory, "/Message/Save", FALSE);
1416         menu_set_sensitive(ifactory, "/Message/Insert file", FALSE);
1417         menu_set_sensitive(ifactory, "/Message/Attach file", FALSE);
1418         menu_set_sensitive(ifactory, "/Message/Insert signature", FALSE);
1419         menu_set_sensitive(ifactory, "/Edit", FALSE);
1420         menu_set_sensitive(ifactory, "/Options", FALSE);
1421         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1422         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1423         
1424         gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1425         gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1426         gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1427         gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1428         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1429         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, FALSE);
1430         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, FALSE);
1431
1432         return compose;
1433 }
1434
1435 GList *compose_get_compose_list(void)
1436 {
1437         return compose_list;
1438 }
1439
1440 void compose_entry_append(Compose *compose, const gchar *address,
1441                           ComposeEntryType type)
1442 {
1443         gchar *header;
1444
1445         if (!address || *address == '\0') return;
1446
1447 #if 0 /* NEW COMPOSE GUI */
1448         switch (type) {
1449         case COMPOSE_CC:
1450                 entry = GTK_ENTRY(compose->cc_entry);
1451                 break;
1452         case COMPOSE_BCC:
1453                 entry = GTK_ENTRY(compose->bcc_entry);
1454                 break;
1455         case COMPOSE_NEWSGROUPS:
1456                 entry = GTK_ENTRY(compose->newsgroups_entry);
1457                 break;
1458         case COMPOSE_TO:
1459         default:
1460                 entry = GTK_ENTRY(compose->to_entry);
1461                 break;
1462         }
1463
1464         text = gtk_entry_get_text(entry);
1465         if (*text != '\0')
1466                 gtk_entry_append_text(entry, ", ");
1467         gtk_entry_append_text(entry, address);
1468 #endif
1469
1470         switch (type) {
1471         case COMPOSE_CC:
1472                 header = N_("Cc:");
1473                 break;
1474         case COMPOSE_BCC:
1475                 header = N_("Bcc:");
1476                 break;
1477         case COMPOSE_REPLYTO:
1478                 header = N_("Reply-To:");
1479                 break;
1480         case COMPOSE_NEWSGROUPS:
1481                 header = N_("Newsgroups:");
1482                 break;
1483         case COMPOSE_FOLLOWUPTO:
1484                 header = N_( "Followup-To:");
1485                 break;
1486         case COMPOSE_TO:
1487         default:
1488                 header = N_("To:");
1489                 break;
1490         }
1491         header = prefs_common.trans_hdr ? gettext(header) : header;
1492
1493         compose_add_header_entry(compose, header, (gchar *)address);
1494 }
1495
1496 void compose_entry_mark_default_to(Compose *compose, const gchar *mailto)
1497 {
1498         static GtkStyle *bold_style = NULL;
1499         static GdkColor bold_color;
1500         GSList *h_list;
1501         GtkEntry *entry;
1502                 
1503         for (h_list = compose->header_list; h_list != NULL; h_list = h_list->next) {
1504                 entry = GTK_ENTRY(((ComposeHeaderEntry *)h_list->data)->entry);
1505                 if (gtk_entry_get_text(entry) && 
1506                     !g_utf8_collate(gtk_entry_get_text(entry), mailto)) {
1507                         gtk_widget_ensure_style(GTK_WIDGET(entry));
1508                         if (!bold_style) {
1509                                 PangoFontDescription *font_desc = NULL;
1510                                 gtkut_convert_int_to_gdk_color
1511                                         (prefs_common.color_new, &bold_color);
1512                                 bold_style = gtk_style_copy(gtk_widget_get_style
1513                                         (GTK_WIDGET(entry)));
1514                                 if (BOLD_FONT)
1515                                         font_desc = pango_font_description_from_string
1516                                                         (BOLD_FONT);
1517                                 if (font_desc) {
1518                                         if (bold_style->font_desc)
1519                                                 pango_font_description_free
1520                                                         (bold_style->font_desc);
1521                                         bold_style->font_desc = font_desc;
1522                                 }
1523                                 bold_style->fg[GTK_STATE_NORMAL] = bold_color;
1524                         }
1525                         gtk_widget_set_style(GTK_WIDGET(entry), bold_style);
1526                 }
1527         }
1528 }
1529
1530 void compose_toolbar_cb(gint action, gpointer data)
1531 {
1532         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1533         Compose *compose = (Compose*)toolbar_item->parent;
1534         
1535         g_return_if_fail(compose != NULL);
1536
1537         switch(action) {
1538         case A_SEND:
1539                 compose_send_cb(compose, 0, NULL);
1540                 break;
1541         case A_SENDL:
1542                 compose_send_later_cb(compose, 0, NULL);
1543                 break;
1544         case A_DRAFT:
1545                 compose_draft_cb(compose, COMPOSE_QUIT_EDITING, NULL);
1546                 break;
1547         case A_INSERT:
1548                 compose_insert_file_cb(compose, 0, NULL);
1549                 break;
1550         case A_ATTACH:
1551                 compose_attach_cb(compose, 0, NULL);
1552                 break;
1553         case A_SIG:
1554                 compose_insert_sig(compose, FALSE);
1555                 break;
1556         case A_EXTEDITOR:
1557                 compose_ext_editor_cb(compose, 0, NULL);
1558                 break;
1559         case A_LINEWRAP_CURRENT:
1560                 compose_wrap_line(compose);
1561                 break;
1562         case A_LINEWRAP_ALL:
1563                 compose_wrap_line_all(compose);
1564                 break;
1565         case A_ADDRBOOK:
1566                 compose_address_cb(compose, 0, NULL);
1567                 break;
1568 #ifdef USE_ASPELL
1569         case A_CHECK_SPELLING:
1570                 compose_check_all(compose);
1571                 break;
1572 #endif
1573         default:
1574                 break;
1575         }
1576 }
1577
1578 static void compose_entries_set(Compose *compose, const gchar *mailto)
1579 {
1580         gchar *to = NULL;
1581         gchar *cc = NULL;
1582         gchar *bcc = NULL;
1583         gchar *subject = NULL;
1584         gchar *body = NULL;
1585         gchar *temp = NULL;
1586         gint  len = 0;
1587
1588         scan_mailto_url(mailto, &to, &cc, &bcc, &subject, &body);
1589
1590         if (to)
1591                 compose_entry_append(compose, to, COMPOSE_TO);
1592         if (cc)
1593                 compose_entry_append(compose, cc, COMPOSE_CC);
1594         if (bcc)
1595                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1596         if (subject)
1597                 if (!g_utf8_validate (subject, -1, NULL)) {
1598                         temp = g_locale_to_utf8 (subject, -1, NULL, &len, NULL);
1599                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), temp);
1600                         g_free(temp);
1601                 } else {
1602                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1603                 }
1604         if (body) {
1605                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1606                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1607                 GtkTextMark *mark;
1608                 GtkTextIter iter;
1609
1610                 mark = gtk_text_buffer_get_insert(buffer);
1611                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1612
1613                 if (!g_utf8_validate (body, -1, NULL)) {
1614                         temp = g_locale_to_utf8 (body, -1, NULL, &len, NULL);
1615                         gtk_text_buffer_insert(buffer, &iter, temp, -1);
1616                         g_free(temp);
1617                 } else {
1618                         gtk_text_buffer_insert(buffer, &iter, body, -1);
1619                 }
1620                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
1621         }
1622
1623         g_free(to);
1624         g_free(cc);
1625         g_free(bcc);
1626         g_free(subject);
1627         g_free(body);
1628 }
1629
1630 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1631 {
1632         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1633                                        {"Cc:",          NULL, TRUE},
1634                                        {"References:",  NULL, FALSE},
1635                                        {"Bcc:",         NULL, TRUE},
1636                                        {"Newsgroups:",  NULL, TRUE},
1637                                        {"Followup-To:", NULL, TRUE},
1638                                        {"List-Post:",   NULL, FALSE},
1639                                        {"X-Priority:",  NULL, FALSE},
1640                                        {NULL,           NULL, FALSE}};
1641
1642         enum
1643         {
1644                 H_REPLY_TO      = 0,
1645                 H_CC            = 1,
1646                 H_REFERENCES    = 2,
1647                 H_BCC           = 3,
1648                 H_NEWSGROUPS    = 4,
1649                 H_FOLLOWUP_TO   = 5,
1650                 H_LIST_POST     = 6,
1651                 H_X_PRIORITY    = 7
1652         };
1653
1654         FILE *fp;
1655
1656         g_return_val_if_fail(msginfo != NULL, -1);
1657
1658         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1659         procheader_get_header_fields(fp, hentry);
1660         fclose(fp);
1661
1662         if (hentry[H_REPLY_TO].body != NULL) {
1663                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1664                 compose->replyto = hentry[H_REPLY_TO].body;
1665                 hentry[H_REPLY_TO].body = NULL;
1666         }
1667         if (hentry[H_CC].body != NULL) {
1668                 conv_unmime_header_overwrite(hentry[H_CC].body);
1669                 compose->cc = hentry[H_CC].body;
1670                 hentry[H_CC].body = NULL;
1671         }
1672         if (hentry[H_REFERENCES].body != NULL) {
1673                 if (compose->mode == COMPOSE_REEDIT)
1674                         compose->references = hentry[H_REFERENCES].body;
1675                 else {
1676                         compose->references = compose_parse_references
1677                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1678                         g_free(hentry[H_REFERENCES].body);
1679                 }
1680                 hentry[H_REFERENCES].body = NULL;
1681         }
1682         if (hentry[H_BCC].body != NULL) {
1683                 if (compose->mode == COMPOSE_REEDIT) {
1684                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1685                         compose->bcc = hentry[H_BCC].body;
1686                 } else
1687                         g_free(hentry[H_BCC].body);
1688                 hentry[H_BCC].body = NULL;
1689         }
1690         if (hentry[H_NEWSGROUPS].body != NULL) {
1691                 conv_unmime_header_overwrite(hentry[H_NEWSGROUPS].body);
1692                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1693                 hentry[H_NEWSGROUPS].body = NULL;
1694         }
1695         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1696                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1697                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1698                 hentry[H_FOLLOWUP_TO].body = NULL;
1699         }
1700         if (hentry[H_LIST_POST].body != NULL) {
1701                 gchar *to = NULL;
1702
1703                 extract_address(hentry[H_LIST_POST].body);
1704                 if (hentry[H_LIST_POST].body[0] != '\0') {
1705                         scan_mailto_url(hentry[H_LIST_POST].body,
1706                                         &to, NULL, NULL, NULL, NULL);
1707                         if (to) {
1708                                 g_free(compose->ml_post);
1709                                 compose->ml_post = to;
1710                         }
1711                 }
1712                 g_free(hentry[H_LIST_POST].body);
1713                 hentry[H_LIST_POST].body = NULL;
1714         }
1715
1716         /* CLAWS - X-Priority */
1717         if (compose->mode == COMPOSE_REEDIT)
1718                 if (hentry[H_X_PRIORITY].body != NULL) {
1719                         gint priority;
1720                         
1721                         priority = atoi(hentry[H_X_PRIORITY].body);
1722                         g_free(hentry[H_X_PRIORITY].body);
1723                         
1724                         hentry[H_X_PRIORITY].body = NULL;
1725                         
1726                         if (priority < PRIORITY_HIGHEST || 
1727                             priority > PRIORITY_LOWEST)
1728                                 priority = PRIORITY_NORMAL;
1729                         
1730                         compose->priority =  priority;
1731                 }
1732  
1733         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1734                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1735         else if (compose->mode != COMPOSE_REEDIT &&
1736                  msginfo->msgid && *msginfo->msgid) {
1737                 compose->inreplyto = g_strdup(msginfo->msgid);
1738
1739                 if (!compose->references) {
1740                         if (msginfo->inreplyto && *msginfo->inreplyto)
1741                                 compose->references =
1742                                         g_strdup_printf("<%s>\n\t<%s>",
1743                                                         msginfo->inreplyto,
1744                                                         msginfo->msgid);
1745                         else
1746                                 compose->references =
1747                                         g_strconcat("<", msginfo->msgid, ">",
1748                                                     NULL);
1749                 }
1750         }
1751
1752         return 0;
1753 }
1754
1755 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1756 {
1757         GSList *ref_id_list, *cur;
1758         GString *new_ref;
1759         gchar *new_ref_str;
1760
1761         ref_id_list = references_list_append(NULL, ref);
1762         if (!ref_id_list) return NULL;
1763         if (msgid && *msgid)
1764                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1765
1766         for (;;) {
1767                 gint len = 0;
1768
1769                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1770                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1771                         len += strlen((gchar *)cur->data) + 5;
1772
1773                 if (len > MAX_REFERENCES_LEN) {
1774                         /* remove second message-ID */
1775                         if (ref_id_list && ref_id_list->next &&
1776                             ref_id_list->next->next) {
1777                                 g_free(ref_id_list->next->data);
1778                                 ref_id_list = g_slist_remove
1779                                         (ref_id_list, ref_id_list->next->data);
1780                         } else {
1781                                 slist_free_strings(ref_id_list);
1782                                 g_slist_free(ref_id_list);
1783                                 return NULL;
1784                         }
1785                 } else
1786                         break;
1787         }
1788
1789         new_ref = g_string_new("");
1790         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1791                 if (new_ref->len > 0)
1792                         g_string_append(new_ref, "\n\t");
1793                 g_string_append_printf(new_ref, "<%s>", (gchar *)cur->data);
1794         }
1795
1796         slist_free_strings(ref_id_list);
1797         g_slist_free(ref_id_list);
1798
1799         new_ref_str = new_ref->str;
1800         g_string_free(new_ref, FALSE);
1801
1802         return new_ref_str;
1803 }
1804
1805 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1806                                 const gchar *fmt, const gchar *qmark,
1807                                 const gchar *body)
1808 {
1809         static MsgInfo dummyinfo;
1810         gchar *quote_str = NULL;
1811         gchar *buf;
1812         gchar *p, *lastp;
1813         gint len;
1814         const gchar *trimmed_body = body;
1815         
1816         if (!msginfo)
1817                 msginfo = &dummyinfo;
1818
1819         if (qmark != NULL) {
1820                 quote_fmt_init(msginfo, NULL, NULL);
1821                 quote_fmt_scan_string(qmark);
1822                 quote_fmt_parse();
1823
1824                 buf = quote_fmt_get_buffer();
1825                 if (buf == NULL)
1826                         alertpanel_error(_("Quote mark format error."));
1827                 else
1828                         Xstrdup_a(quote_str, buf, return NULL)
1829         }
1830
1831         if (fmt && *fmt != '\0') {
1832                 while (trimmed_body && strlen(trimmed_body) > 1
1833                         && trimmed_body[0]=='\n')
1834                         *trimmed_body++;
1835
1836                 quote_fmt_init(msginfo, quote_str, trimmed_body);
1837                 quote_fmt_scan_string(fmt);
1838                 quote_fmt_parse();
1839
1840                 buf = quote_fmt_get_buffer();
1841                 if (buf == NULL) {
1842                         alertpanel_error(_("Message reply/forward format error."));
1843                         return NULL;
1844                 }
1845         } else
1846                 buf = "";
1847
1848         for (p = buf; *p != '\0'; ) {
1849                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1850                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1851                 GtkTextMark *mark;
1852                 GtkTextIter iter;
1853
1854                 g_signal_handlers_block_by_func(G_OBJECT(buffer),
1855                                         G_CALLBACK(compose_changed_cb),
1856                                         compose);
1857                 g_signal_handlers_block_by_func(G_OBJECT(buffer),
1858                                         G_CALLBACK(text_inserted),
1859                                         compose);
1860                 
1861                 mark = gtk_text_buffer_get_insert(buffer);
1862                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1863
1864                 lastp = strchr(p, '\n');
1865                 len = lastp ? lastp - p + 1 : -1;
1866
1867                 gtk_text_buffer_insert(buffer, &iter, p, len);
1868
1869                 g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
1870                                         G_CALLBACK(compose_changed_cb),
1871                                         compose);
1872                 g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
1873                                         G_CALLBACK(text_inserted),
1874                                         compose);
1875                 
1876                 if (lastp)
1877                         p = lastp + 1;
1878                 else
1879                         break;
1880         }
1881
1882         return buf;
1883 }
1884
1885 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1886                                     gboolean to_all, gboolean to_ml,
1887                                     gboolean to_sender,
1888                                     gboolean followup_and_reply_to)
1889 {
1890         GSList *cc_list = NULL;
1891         GSList *cur;
1892         gchar *from = NULL;
1893         gchar *replyto = NULL;
1894         GHashTable *to_table;
1895
1896         g_return_if_fail(compose->account != NULL);
1897         g_return_if_fail(msginfo != NULL);
1898
1899         if (compose->account->protocol != A_NNTP) {
1900                 if (!compose->replyto && to_ml && compose->ml_post
1901                     && !(msginfo->folder && msginfo->folder->prefs->enable_default_reply_to))
1902                         compose_entry_append(compose,
1903                                            compose->ml_post,
1904                                            COMPOSE_TO);
1905                 else if (!(to_all || to_sender)
1906                          && msginfo->folder
1907                          && msginfo->folder->prefs->enable_default_reply_to) {
1908                         compose_entry_append(compose,
1909                             msginfo->folder->prefs->default_reply_to,
1910                             COMPOSE_TO);
1911                 } else
1912                         compose_entry_append(compose,
1913                                  (compose->replyto && !to_sender)
1914                                   ? compose->replyto :
1915                                   msginfo->from ? msginfo->from : "",
1916                                   COMPOSE_TO);
1917         } else {
1918                 if (to_sender || (compose->followup_to && 
1919                         !strncmp(compose->followup_to, "poster", 6)))
1920                         compose_entry_append
1921                                 (compose, 
1922                                  (compose->replyto ? compose->replyto :
1923                                         msginfo->from ? msginfo->from : ""),
1924                                  COMPOSE_TO);
1925                                  
1926                 else if (followup_and_reply_to || to_all) {
1927                         compose_entry_append
1928                                 (compose,
1929                                  (compose->replyto ? compose->replyto :
1930                                  msginfo->from ? msginfo->from : ""),
1931                                  COMPOSE_TO);                           
1932                 
1933                         compose_entry_append
1934                                 (compose,
1935                                  compose->followup_to ? compose->followup_to :
1936                                  compose->newsgroups ? compose->newsgroups : "",
1937                                  COMPOSE_NEWSGROUPS);
1938                 } 
1939                 else 
1940                         compose_entry_append
1941                                 (compose,
1942                                  compose->followup_to ? compose->followup_to :
1943                                  compose->newsgroups ? compose->newsgroups : "",
1944                                  COMPOSE_NEWSGROUPS);
1945         }
1946
1947         if (msginfo->subject && *msginfo->subject) {
1948                 gchar *buf, *buf2;
1949                 guchar *p;
1950
1951                 buf = p = g_strdup(msginfo->subject);
1952                 p += subject_get_prefix_length(p);
1953                 memmove(buf, p, strlen(p) + 1);
1954
1955                 buf2 = g_strdup_printf("Re: %s", buf);
1956                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1957
1958                 g_free(buf2);
1959                 g_free(buf);
1960         } else
1961                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1962
1963         if (to_ml && compose->ml_post) return;
1964         if (!to_all || compose->account->protocol == A_NNTP) return;
1965
1966         if (compose->replyto) {
1967                 Xstrdup_a(replyto, compose->replyto, return);
1968                 extract_address(replyto);
1969         }
1970         if (msginfo->from) {
1971                 Xstrdup_a(from, msginfo->from, return);
1972                 extract_address(from);
1973         }
1974
1975         if (replyto && from)
1976                 cc_list = address_list_append_with_comments(cc_list, from);
1977         if (to_all && msginfo->folder && 
1978             msginfo->folder->prefs->enable_default_reply_to)
1979                 cc_list = address_list_append_with_comments(cc_list,
1980                                 msginfo->folder->prefs->default_reply_to);
1981         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
1982         cc_list = address_list_append_with_comments(cc_list, compose->cc);
1983
1984         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1985         if (replyto)
1986                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
1987         if (compose->account)
1988                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
1989                                     GINT_TO_POINTER(1));
1990
1991         /* remove address on To: and that of current account */
1992         for (cur = cc_list; cur != NULL; ) {
1993                 GSList *next = cur->next;
1994                 gchar *addr;
1995
1996                 addr = g_strdup(cur->data);
1997                 extract_address(addr);
1998
1999                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
2000                         cc_list = g_slist_remove(cc_list, cur->data);
2001                 else
2002                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
2003
2004                 cur = next;
2005         }
2006         hash_free_strings(to_table);
2007         g_hash_table_destroy(to_table);
2008
2009         if (cc_list) {
2010                 for (cur = cc_list; cur != NULL; cur = cur->next)
2011                         compose_entry_append(compose, (gchar *)cur->data,
2012                                              COMPOSE_CC);
2013                 slist_free_strings(cc_list);
2014                 g_slist_free(cc_list);
2015         }
2016
2017 }
2018
2019 #define SET_ENTRY(entry, str) \
2020 { \
2021         if (str && *str) \
2022                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
2023 }
2024
2025 #define SET_ADDRESS(type, str) \
2026 { \
2027         if (str && *str) \
2028                 compose_entry_append(compose, str, type); \
2029 }
2030
2031 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
2032 {
2033         g_return_if_fail(msginfo != NULL);
2034
2035         SET_ENTRY(subject_entry, msginfo->subject);
2036         SET_ADDRESS(COMPOSE_TO, msginfo->to);
2037         SET_ADDRESS(COMPOSE_CC, compose->cc);
2038         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
2039         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
2040         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
2041         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2042
2043         compose_update_priority_menu_item(compose);
2044         compose_update_privacy_system_menu_item(compose);
2045         compose_show_first_last_header(compose, TRUE);
2046 }
2047
2048 #undef SET_ENTRY
2049 #undef SET_ADDRESS
2050
2051 static void compose_insert_sig(Compose *compose, gboolean replace)
2052 {
2053         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2054         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2055         GtkTextMark *mark;
2056         GtkTextIter iter;
2057         gint cur_pos;
2058
2059         
2060         g_return_if_fail(compose->account != NULL);
2061
2062         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2063                                         G_CALLBACK(compose_changed_cb),
2064                                         compose);
2065         
2066         mark = gtk_text_buffer_get_insert(buffer);
2067         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2068         cur_pos = gtk_text_iter_get_offset (&iter);
2069
2070         gtk_text_buffer_get_end_iter(buffer, &iter);
2071
2072         if (replace && compose->sig_str) {
2073                 gboolean found;
2074                 GtkTextIter first_iter, start_iter, end_iter;
2075
2076                 gtk_text_buffer_get_start_iter(buffer, &first_iter);
2077
2078                 if (compose->sig_str[0] == '\0')
2079                         found = FALSE;
2080                 else
2081                         found = gtk_text_iter_forward_search(&first_iter,
2082                                                              compose->sig_str,
2083                                                              GTK_TEXT_SEARCH_TEXT_ONLY,
2084                                                              &start_iter, &end_iter,
2085                                                              NULL);
2086
2087                 if (found) {
2088                         gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
2089                         iter = start_iter;
2090                 }
2091         }
2092
2093         g_free(compose->sig_str);
2094         compose->sig_str = compose_get_signature_str(compose);
2095         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2096                 compose->sig_str = g_strdup("");
2097
2098         gtk_text_buffer_insert(buffer, &iter, compose->sig_str, -1);
2099
2100         if (cur_pos > gtk_text_buffer_get_char_count (buffer))
2101                 cur_pos = gtk_text_buffer_get_char_count (buffer);
2102
2103         gtk_text_buffer_get_iter_at_offset (buffer, &iter, cur_pos);
2104         gtk_text_buffer_place_cursor (buffer, &iter);
2105
2106         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2107                                         G_CALLBACK(compose_changed_cb),
2108                                         compose);
2109         
2110 }
2111
2112 static gchar *compose_get_signature_str(Compose *compose)
2113 {
2114         gchar *sig_body = NULL;
2115         gchar *sig_str = NULL;
2116
2117         g_return_val_if_fail(compose->account != NULL, NULL);
2118
2119         if (!compose->account->sig_path)
2120                 return NULL;
2121
2122         if (compose->account->sig_type == SIG_FILE) {
2123                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2124                         g_warning("can't open signature file: %s\n",
2125                                   compose->account->sig_path);
2126                         return NULL;
2127                 }
2128         }
2129
2130         if (compose->account->sig_type == SIG_COMMAND)
2131                 sig_body = get_command_output(compose->account->sig_path);
2132         else {
2133                 gchar *tmp;
2134
2135                 tmp = file_read_to_str(compose->account->sig_path);
2136                 if (!tmp)
2137                         return NULL;
2138                 sig_body = normalize_newlines(tmp);
2139                 g_free(tmp);
2140         }
2141
2142         if (compose->account->sig_sep)
2143                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2144                                       NULL);
2145         else
2146                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2147
2148         g_free(sig_body);
2149         
2150         return sig_str;
2151 }
2152
2153 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2154 {
2155         GtkTextView *text;
2156         GtkTextBuffer *buffer;
2157         GtkTextMark *mark;
2158         GtkTextIter iter;
2159         const gchar *cur_encoding;
2160         gchar buf[BUFFSIZE];
2161         gint len;
2162         FILE *fp;
2163         gboolean badtxt = FALSE;
2164
2165         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2166
2167         if ((fp = fopen(file, "rb")) == NULL) {
2168                 FILE_OP_ERROR(file, "fopen");
2169                 return COMPOSE_INSERT_READ_ERROR;
2170         }
2171
2172         text = GTK_TEXT_VIEW(compose->text);
2173         buffer = gtk_text_view_get_buffer(text);
2174         mark = gtk_text_buffer_get_insert(buffer);
2175         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2176
2177         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2178                                         G_CALLBACK(text_inserted),
2179                                         compose);
2180
2181         cur_encoding = conv_get_locale_charset_str();
2182
2183         while (fgets(buf, sizeof(buf), fp) != NULL) {
2184                 gchar *str;
2185
2186                 str = conv_codeset_strdup(buf, cur_encoding, CS_INTERNAL);
2187                 if (!str) continue;
2188
2189                 /* strip <CR> if DOS/Windows file,
2190                    replace <CR> with <LF> if Macintosh file. */
2191                 strcrchomp(str);
2192                 len = strlen(str);
2193                 if (len > 0 && str[len - 1] != '\n') {
2194                         while (--len >= 0)
2195                                 if (str[len] == '\r') str[len] = '\n';
2196                 }
2197
2198                 gtk_text_buffer_insert(buffer, &iter, str, -1);
2199                 g_free(str);
2200         }
2201
2202         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2203                                           G_CALLBACK(text_inserted),
2204                                           compose);
2205
2206         fclose(fp);
2207
2208         if (badtxt)
2209                 return COMPOSE_INSERT_INVALID_CHARACTER;
2210         else 
2211                 return COMPOSE_INSERT_SUCCESS;
2212 }
2213
2214 static void compose_attach_append(Compose *compose, const gchar *file,
2215                                   const gchar *filename,
2216                                   const gchar *content_type)
2217 {
2218         AttachInfo *ainfo;
2219         GtkTreeIter iter;
2220         FILE *fp;
2221         off_t size;
2222         GAuto *auto_ainfo;
2223         gchar *size_text;
2224         GtkListStore *store;
2225         gchar *name;
2226
2227         if (!is_file_exist(file)) {
2228                 g_warning("File %s doesn't exist\n", file);
2229                 return;
2230         }
2231         if ((size = get_file_size(file)) < 0) {
2232                 g_warning("Can't get file size of %s\n", file);
2233                 return;
2234         }
2235         if (size == 0) {
2236                 alertpanel_notice(_("File %s is empty."), file);
2237                 return;
2238         }
2239         if ((fp = fopen(file, "rb")) == NULL) {
2240                 alertpanel_error(_("Can't read %s."), file);
2241                 return;
2242         }
2243         fclose(fp);
2244
2245 #if 0 /* NEW COMPOSE GUI */
2246         if (!compose->use_attach) {
2247                 GtkItemFactory *ifactory;
2248
2249                 ifactory = gtk_item_factory_from_widget(compose->menubar);
2250                 menu_set_active(ifactory, "/View/Attachment", TRUE);
2251         }
2252 #endif
2253         ainfo = g_new0(AttachInfo, 1);
2254         auto_ainfo = g_auto_pointer_new_with_free
2255                         (ainfo, (GFreeFunc) compose_attach_info_free); 
2256         ainfo->file = g_strdup(file);
2257
2258         if (content_type) {
2259                 ainfo->content_type = g_strdup(content_type);
2260                 if (!g_ascii_strcasecmp(content_type, "message/rfc822")) {
2261                         MsgInfo *msginfo;
2262                         MsgFlags flags = {0, 0};
2263
2264                         if (procmime_get_encoding_for_text_file(file) == ENC_7BIT)
2265                                 ainfo->encoding = ENC_7BIT;
2266                         else
2267                                 ainfo->encoding = ENC_8BIT;
2268
2269                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2270                         if (msginfo && msginfo->subject)
2271                                 name = g_strdup(msginfo->subject);
2272                         else
2273                                 name = g_path_get_basename(filename ? filename : file);
2274
2275                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2276
2277                         procmsg_msginfo_free(msginfo);
2278                 } else {
2279                         if (!g_ascii_strncasecmp(content_type, "text", 4))
2280                                 ainfo->encoding = procmime_get_encoding_for_text_file(file);
2281                         else
2282                                 ainfo->encoding = ENC_BASE64;
2283                         name = g_path_get_basename(filename ? filename : file);
2284                         ainfo->name = g_strdup(name);
2285                 }
2286                 g_free(name);
2287         } else {
2288                 ainfo->content_type = procmime_get_mime_type(file);
2289                 if (!ainfo->content_type) {
2290                         ainfo->content_type =
2291                                 g_strdup("application/octet-stream");
2292                         ainfo->encoding = ENC_BASE64;
2293                 } else if (!g_ascii_strncasecmp(ainfo->content_type, "text", 4))
2294                         ainfo->encoding =
2295                                 procmime_get_encoding_for_text_file(file);
2296                 else
2297                         ainfo->encoding = ENC_BASE64;
2298                 name = g_path_get_basename(filename ? filename : file);
2299                 ainfo->name = g_strdup(name);   
2300                 g_free(name);
2301         }
2302
2303         if (!strcmp(ainfo->content_type, "unknown")) {
2304                 g_free(ainfo->content_type);
2305                 ainfo->content_type = g_strdup("application/octet-stream");
2306         }
2307
2308         ainfo->size = size;
2309         size_text = to_human_readable(size);
2310
2311         store = GTK_LIST_STORE(gtk_tree_view_get_model
2312                         (GTK_TREE_VIEW(compose->attach_clist)));
2313                 
2314         gtk_list_store_append(store, &iter);
2315         gtk_list_store_set(store, &iter, 
2316                            COL_MIMETYPE, ainfo->content_type,
2317                            COL_SIZE, size_text,
2318                            COL_NAME, ainfo->name,
2319                            COL_DATA, ainfo,
2320                            COL_AUTODATA, auto_ainfo,
2321                            -1);
2322         
2323         g_auto_pointer_free(auto_ainfo);
2324 }
2325
2326 static void compose_use_signing(Compose *compose, gboolean use_signing)
2327 {
2328         GtkItemFactory *ifactory;
2329         GtkWidget *menuitem = NULL;
2330
2331         compose->use_signing = use_signing;
2332         ifactory = gtk_item_factory_from_widget(compose->menubar);
2333         menuitem = gtk_item_factory_get_item
2334                 (ifactory, "/Options/Sign");
2335         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2336                                        use_signing);
2337 }
2338
2339 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2340 {
2341         GtkItemFactory *ifactory;
2342         GtkWidget *menuitem = NULL;
2343
2344         compose->use_encryption = use_encryption;
2345         ifactory = gtk_item_factory_from_widget(compose->menubar);
2346         menuitem = gtk_item_factory_get_item
2347                 (ifactory, "/Options/Encrypt");
2348
2349         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2350                                        use_encryption);
2351 }
2352
2353 #define NEXT_PART_NOT_CHILD(info)  \
2354 {  \
2355         node = info->node;  \
2356         while (node->children)  \
2357                 node = g_node_last_child(node);  \
2358         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2359 }
2360
2361 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2362 {
2363         MimeInfo *mimeinfo;
2364         MimeInfo *child;
2365         MimeInfo *firsttext = NULL;
2366         MimeInfo *encrypted = NULL;
2367         GNode    *node;
2368         gchar *outfile;
2369         const gchar *partname = NULL;
2370
2371         mimeinfo = procmime_scan_message(msginfo);
2372         if (!mimeinfo) return;
2373
2374         if (mimeinfo->node->children == NULL) {
2375                 procmime_mimeinfo_free_all(mimeinfo);
2376                 return;
2377         }
2378
2379         /* find first content part */
2380         child = (MimeInfo *) mimeinfo->node->children->data;
2381         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2382                 child = (MimeInfo *)child->node->children->data;
2383
2384         if (child->type == MIMETYPE_TEXT) {
2385                 firsttext = child;
2386                 debug_print("First text part found\n");
2387         } else if (compose->mode == COMPOSE_REEDIT &&
2388                  child->type == MIMETYPE_APPLICATION &&
2389                  !g_ascii_strcasecmp(child->subtype, "pgp-encrypted")) {
2390                 AlertValue val;
2391                 val = alertpanel(_("Encrypted message"),
2392                                  _("Cannot re-edit an encrypted message. \n"
2393                                    "Discard encrypted part?"),
2394                                  _("Yes"), _("No"), NULL);
2395                 if (val == G_ALERTDEFAULT) 
2396                         encrypted = (MimeInfo *)child->node->parent->data;
2397         }
2398      
2399         child = (MimeInfo *) mimeinfo->node->children->data;
2400         while (child != NULL) {
2401                 if (child == encrypted) {
2402                         /* skip this part of tree */
2403                         NEXT_PART_NOT_CHILD(child);
2404                         continue;
2405                 }
2406
2407                 if (child->type == MIMETYPE_MULTIPART) {
2408                         /* get the actual content */
2409                         child = procmime_mimeinfo_next(child);
2410                         continue;
2411                 }
2412                     
2413                 if (child == firsttext) {
2414                         child = procmime_mimeinfo_next(child);
2415                         continue;
2416                 }
2417
2418                 outfile = procmime_get_tmp_file_name(child);
2419                 if (procmime_get_part(outfile, child) < 0)
2420                         g_warning("Can't get the part of multipart message.");
2421                 else {
2422                         gchar *content_type;
2423
2424                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2425                         partname = procmime_mimeinfo_get_parameter(child, "name");
2426                         if (partname == NULL)
2427                                 partname = "";
2428                         compose_attach_append(compose, outfile, 
2429                                               partname, content_type);
2430                         g_free(content_type);
2431                 }
2432                 g_free(outfile);
2433                 NEXT_PART_NOT_CHILD(child);
2434         }
2435         procmime_mimeinfo_free_all(mimeinfo);
2436 }
2437
2438   
2439 #define CHAR_BUF_SIZE 8
2440 #undef NEXT_PART_NOT_CHILD
2441
2442
2443 #define GET_CHAR(iter_p, buf, len)                              \
2444 {                                                               \
2445         gunichar uc;                                            \
2446                                                                 \
2447         uc = gtk_text_iter_get_char(iter_p);                    \
2448         if (uc != 0)                                            \
2449                 len = g_unichar_to_utf8(uc, buf) > 1 ? 2 : 1;   \
2450         else {                                                  \
2451                 buf[0] = '\0';                                  \
2452                 len = 1;                                        \
2453         }                                                       \
2454 }
2455 #define DISP_WIDTH(len) \
2456         ((len > 2 && conv_get_locale_charset() == C_UTF_8) ? 2 : \
2457          (len == 2 && conv_get_locale_charset() == C_UTF_8) ? 1 : len)
2458
2459 #define SPACE_CHARS     " \t"
2460
2461 static void compose_wrap_line(Compose *compose)
2462 {
2463         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2464         GtkTextBuffer *textbuf = gtk_text_view_get_buffer(text);
2465         GtkTextMark *mark;
2466         GtkTextIter insert_iter, iter;
2467         gint ch_len, last_ch_len;
2468         gchar cbuf[CHAR_BUF_SIZE], last_ch;
2469         guint text_len;
2470         gint p_start, p_end;
2471         gint line_pos, cur_pos;
2472         gint line_len, cur_len;
2473         gboolean line_end, quoted;
2474
2475         text_len = gtk_text_buffer_get_char_count(textbuf);
2476         mark = gtk_text_buffer_get_insert(textbuf);
2477         gtk_text_buffer_get_iter_at_mark(textbuf, &insert_iter, mark);
2478         cur_pos = gtk_text_iter_get_offset(&insert_iter);
2479         GET_CHAR(&insert_iter, cbuf, ch_len);
2480         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
2481                 GtkTextIter prev_iter;
2482                 if (cur_pos == 0)
2483                         return; /* on the paragraph mark */
2484                 prev_iter = insert_iter;
2485                 gtk_text_iter_backward_char(&prev_iter);
2486                 GET_CHAR(&prev_iter, cbuf, ch_len);
2487                 if (ch_len == 1 && *cbuf == '\n')
2488                         return; /* on the paragraph mark */
2489         }
2490
2491         /* find paragraph start. */
2492         line_end = quoted = FALSE;
2493         for (iter = insert_iter; gtk_text_iter_backward_char(&iter);) {
2494                 GET_CHAR(&iter, cbuf, ch_len);
2495                 if (ch_len == 1 && *cbuf == '\n') {
2496                         if (quoted)
2497                                 return; /* quoted part */
2498                         if (line_end) {
2499                                 gtk_text_iter_forward_chars(&iter, 2);
2500                                 break;
2501                         }
2502                         line_end = TRUE;
2503                 } else {
2504                         if (ch_len == 1 
2505                             && strchr(prefs_common.quote_chars, *cbuf))
2506                                 quoted = 1;
2507                         else if (ch_len != 1 || !isspace(*(guchar *)cbuf))
2508                                 quoted = 0;
2509
2510                         line_end = FALSE;
2511                 }
2512         }
2513         p_start = gtk_text_iter_get_offset(&iter);
2514
2515         /* find paragraph end. */
2516         line_end = FALSE;
2517         for (iter = insert_iter; gtk_text_iter_forward_char(&iter);) {
2518                 GET_CHAR(&iter, cbuf, ch_len);
2519                 if (ch_len == 1 && *cbuf == '\n') {
2520                         if (line_end) {
2521                                 p_end -= 1;
2522                                 gtk_text_iter_backward_char(&iter);
2523                                 break;
2524                         }
2525                         line_end = TRUE;
2526                 } else {
2527                         if (line_end && ch_len == 1 &&
2528                             strchr(prefs_common.quote_chars, *cbuf))
2529                                 return; /* quoted part */
2530
2531                         line_end = FALSE;
2532                 }
2533         }
2534         p_end = gtk_text_iter_get_offset(&iter);
2535
2536         if (p_end >= text_len)
2537                 p_end = text_len;
2538
2539         if (p_start >= p_end)
2540                 return;
2541
2542         line_len = cur_len = 0;
2543         last_ch_len = 0;
2544         last_ch = '\0';
2545         line_pos = p_start;
2546         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2547                 gboolean space = FALSE;
2548
2549                 gtk_text_buffer_get_iter_at_offset(textbuf, &iter, cur_pos);
2550
2551                 GET_CHAR(&iter, cbuf, ch_len);
2552
2553                 if (ch_len < 0) {
2554                         cbuf[0] = '\0';
2555                         ch_len = 1;
2556                 }
2557
2558                 if (ch_len == 1 && isspace(*(guchar *)cbuf))
2559                         space = 1;
2560
2561                 if (ch_len == 1 && *cbuf == '\n') {
2562                         gboolean replace = FALSE;
2563                         GtkTextIter next_iter = iter;
2564
2565                         gtk_text_iter_forward_char(&next_iter);
2566
2567                         if (last_ch_len == 1 && !isspace((guchar)last_ch)) {
2568                                 if (cur_pos + 1 < p_end) {
2569                                         GET_CHAR(&next_iter, cbuf, ch_len);
2570                                         if (ch_len == 1 &&
2571                                             !isspace(*(guchar *)cbuf))
2572                                                 replace = TRUE;
2573                                 }
2574                         }
2575                         gtk_text_buffer_delete(textbuf, &iter, &next_iter);
2576                         if (replace) {
2577                                 gtk_text_buffer_insert(textbuf, &iter, " ", 1);
2578                                 space = TRUE;
2579                         }
2580                         else {
2581                                 p_end--;
2582                                 cur_pos--;
2583                                 gtk_text_buffer_get_iter_at_offset
2584                                         (textbuf, &iter, cur_pos);
2585                                 continue;
2586                         }
2587                 }
2588
2589                 last_ch_len = ch_len;
2590                 last_ch = *cbuf;
2591
2592                 if (space) {
2593                         line_pos = cur_pos + 1;
2594                         line_len = cur_len + ch_len;
2595                 }
2596
2597                 gtk_text_buffer_get_iter_at_offset(textbuf, &iter, line_pos);
2598
2599                 if (cur_len + ch_len > prefs_common.linewrap_len &&
2600                     line_len > 0) {
2601                         gint tlen = ch_len;
2602                         GtkTextIter prev_iter = iter;
2603
2604                         gtk_text_iter_backward_char(&prev_iter);
2605
2606                         GET_CHAR(&prev_iter, cbuf, ch_len);
2607                         if (ch_len == 1 && isspace(*(guchar *)cbuf)) {
2608                                 gtk_text_buffer_delete(textbuf, &prev_iter, &iter);
2609                                 iter = prev_iter;
2610                                 p_end--;
2611                                 cur_pos--;
2612                                 line_pos--;
2613                                 cur_len--;
2614                                 line_len--;
2615                         }
2616                         ch_len = tlen;
2617
2618                         gtk_text_buffer_insert(textbuf, &iter, "\n", 1);
2619                         p_end++;
2620                         cur_pos++;
2621                         line_pos++;
2622                         cur_len = cur_len - line_len + ch_len;
2623                         line_len = 0;
2624                         continue;
2625                 }
2626
2627                 if (ch_len > 1) {
2628                         line_pos = cur_pos + 1;
2629                         line_len = cur_len + ch_len;
2630                 }
2631                 cur_len += ch_len;
2632         }
2633 }
2634
2635 #undef WRAP_DEBUG
2636 #ifdef WRAP_DEBUG
2637 /* Darko: used when I debug wrapping */
2638 void dump_text(GtkTextBuffer *textbuf, int pos, int tlen, int breakoncr)
2639 {
2640         GtkTextIter iter, end_iter;
2641         gint clen;
2642         gchar cbuf[CHAR_BUF_SIZE];
2643
2644         printf("%d [", pos);
2645         gtk_text_buffer_get_iter_at_offset(textbuf, &iter, pos);
2646         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter, pos + tlen);
2647         for (; gtk_text_iter_forward_char(&iter) &&
2648              gtk_text_iter_compare(&iter, &end_iter) < 0; ) {
2649                 GET_CHAR(&iter, cbuf, clen);
2650                 if (clen < 0) break;
2651                 if (breakoncr && clen == 1 && cbuf[0] == '\n')
2652                         break;
2653                 fwrite(cbuf, clen, 1, stdout);
2654         }
2655         printf("]\n");
2656 }
2657 #endif
2658
2659 typedef enum {
2660         WAIT_FOR_SPACE,
2661         WAIT_FOR_INDENT_CHAR,
2662         WAIT_FOR_INDENT_CHAR_OR_SPACE
2663 } IndentState;
2664
2665 /* return indent length, we allow:
2666    > followed by spaces/tabs
2667    | followed by spaces/tabs
2668    uppercase characters immediately followed by >,
2669    and the repeating sequences of the above */
2670 /* return indent length */
2671 static guint get_indent_length(GtkTextBuffer *textbuf, guint start_pos,
2672                                guint text_len)
2673 {
2674         GtkTextIter iter;
2675         guint i_len = 0;
2676         guint ch_len, alnum_cnt = 0;
2677         IndentState state = WAIT_FOR_INDENT_CHAR;
2678         gchar cbuf[CHAR_BUF_SIZE];
2679         gboolean is_space;
2680         gboolean is_indent;
2681         gboolean iter_next = TRUE;
2682
2683         if (prefs_common.quote_chars == NULL) {
2684                 return 0 ;
2685         }
2686
2687         gtk_text_buffer_get_iter_at_offset(textbuf, &iter, start_pos);
2688
2689         while (iter_next == TRUE) {
2690                 GET_CHAR(&iter, cbuf, ch_len);
2691                 if (ch_len > 1)
2692                         break;
2693
2694                 if (cbuf[0] == '\n')
2695                         break;
2696
2697                 is_indent = strchr(prefs_common.quote_chars, cbuf[0]) ? TRUE : FALSE;
2698                 is_space = strchr(SPACE_CHARS, cbuf[0]) ? TRUE : FALSE;
2699
2700                 switch (state) {
2701                 case WAIT_FOR_SPACE:
2702                         if (is_space == FALSE)
2703                                 goto out;
2704                         state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2705                         break;
2706                 case WAIT_FOR_INDENT_CHAR_OR_SPACE:
2707                         if (is_indent == FALSE && is_space == FALSE &&
2708                             !isupper((guchar)cbuf[0]))
2709                                 goto out;
2710                         if (is_space == TRUE) {
2711                                 alnum_cnt = 0;
2712                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2713                         } else if (is_indent == TRUE) {
2714                                 alnum_cnt = 0;
2715                                 state = WAIT_FOR_SPACE;
2716                         } else {
2717                                 alnum_cnt++;
2718                                 state = WAIT_FOR_INDENT_CHAR;
2719                         }
2720                         break;
2721                 case WAIT_FOR_INDENT_CHAR:
2722                         if (is_indent == FALSE && !isupper((guchar)cbuf[0]))
2723                                 goto out;
2724                         if (is_indent == TRUE) {
2725                                 if (alnum_cnt > 0 
2726                                     && !strchr(prefs_common.quote_chars, cbuf[0]))
2727                                         goto out;
2728                                 alnum_cnt = 0;
2729                                 state = WAIT_FOR_SPACE;
2730                         } else {
2731                                 alnum_cnt++;
2732                         }
2733                         break;
2734                 }
2735
2736                 i_len++;
2737                 iter_next = gtk_text_iter_forward_char(&iter);
2738         }
2739
2740 out:
2741         if ((i_len > 0) && (state == WAIT_FOR_INDENT_CHAR))
2742                 i_len -= alnum_cnt;
2743
2744         return i_len;
2745 }
2746
2747 /* insert quotation string when line was wrapped */
2748 static guint ins_quote(GtkTextBuffer *textbuf, GtkTextIter *iter,
2749                        guint indent_len,
2750                        guint prev_line_pos, guint text_len,
2751                        gchar *quote_fmt)
2752 {
2753         guint ins_len = 0;
2754
2755         if (indent_len) {
2756                 GtkTextIter iter1, iter2;
2757                 gchar *text;
2758
2759                 gtk_text_buffer_get_iter_at_offset(textbuf, &iter1,
2760                                                    prev_line_pos);
2761                 gtk_text_buffer_get_iter_at_offset(textbuf, &iter2,
2762                                                    prev_line_pos + indent_len);
2763                 text = gtk_text_buffer_get_text(textbuf, &iter1, &iter2, FALSE);
2764                 if (!text) return 0;
2765
2766                 gtk_text_buffer_insert(textbuf, iter, text, -1);
2767                 ins_len = g_utf8_strlen(text, -1);
2768
2769                 g_free(text);
2770         }
2771
2772         return ins_len;
2773 }
2774
2775 static gboolean is_sig_separator(Compose *compose, GtkTextBuffer *textbuf, guint start_pos) 
2776 {
2777         char *text = NULL;
2778         GtkTextIter iter; 
2779         GtkTextIter end_iter;
2780         if (!compose->account->sig_sep)
2781                 return FALSE;
2782         
2783         gtk_text_buffer_get_iter_at_offset(textbuf, &iter, start_pos+1);
2784         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
2785                 start_pos+strlen(compose->account->sig_sep)+1);
2786
2787         if (!strcmp(gtk_text_iter_get_text(&iter, &end_iter),
2788                         compose->account->sig_sep)) {
2789                 /* check \n */
2790                 gtk_text_buffer_get_iter_at_offset(textbuf, &iter,
2791                         start_pos+strlen(compose->account->sig_sep)+1);
2792                 gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
2793                         start_pos+strlen(compose->account->sig_sep)+2);
2794
2795                 if (!strcmp(gtk_text_iter_get_text(&iter, &end_iter),"\n"));
2796                         return TRUE;
2797                 
2798
2799         }
2800
2801         return FALSE;
2802 }
2803
2804 /* check if we should join the next line */
2805 static gboolean join_next_line_is_needed(GtkTextBuffer *textbuf,
2806                                          guint start_pos, guint tlen,
2807                                          guint prev_ilen, gboolean autowrap)
2808 {
2809         guint indent_len, ch_len;
2810         gboolean do_join = FALSE;
2811         gchar cbuf[CHAR_BUF_SIZE];
2812
2813         indent_len = get_indent_length(textbuf, start_pos, tlen);
2814
2815         if ((autowrap || indent_len > 0) && indent_len == prev_ilen) {
2816                 GtkTextIter iter;
2817                 gtk_text_buffer_get_iter_at_offset(textbuf, &iter,
2818                                                    start_pos + indent_len);
2819                 GET_CHAR(&iter, cbuf, ch_len);
2820                 
2821                 if (ch_len > 0 && (cbuf[0] != '\n'))
2822                         do_join = TRUE;
2823         }
2824
2825         return do_join;
2826 }
2827
2828 static void compose_wrap_line_all(Compose *compose)
2829 {
2830         compose_wrap_line_all_full(compose, FALSE);
2831 }
2832
2833 static void compose_wrap_line_all_full(Compose *compose, gboolean autowrap)
2834 {
2835         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2836         GtkTextBuffer *textbuf = gtk_text_view_get_buffer(text);
2837         GtkTextIter iter, end_iter;
2838         guint tlen;
2839         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2840         gint line_len = 0, cur_len = 0;
2841         gint ch_len;
2842         gboolean is_new_line = TRUE, do_delete = FALSE;
2843         guint i_len = 0;
2844         gboolean linewrap_quote = prefs_common.linewrap_quote;
2845         gboolean set_editable_pos = FALSE;
2846         gint editable_pos = 0;
2847         guint linewrap_len = prefs_common.linewrap_len;
2848         gchar *qfmt = prefs_common.quotemark;
2849         gchar cbuf[CHAR_BUF_SIZE];
2850         GtkTextMark *cursor_mark = gtk_text_buffer_get_insert(textbuf);
2851         
2852         tlen = gtk_text_buffer_get_char_count(textbuf);
2853
2854         for (; cur_pos < tlen; cur_pos++) {
2855                 /* mark position of new line - needed for quotation wrap */
2856                 if (is_new_line) {
2857                         if (linewrap_quote)
2858                                 i_len = get_indent_length(textbuf, cur_pos, tlen);
2859
2860                         is_new_line = FALSE;
2861                         p_pos = cur_pos;
2862                 }
2863
2864                 gtk_text_buffer_get_iter_at_offset(textbuf, &iter, cur_pos);
2865                 GET_CHAR(&iter, cbuf, ch_len);
2866
2867                 /* fix line length for tabs */
2868                 if (ch_len == 1 && *cbuf == '\t') {
2869                         guint tab_width = 8;
2870                         guint tab_offset = line_len % tab_width;
2871
2872                         line_len += tab_width - tab_offset - 1;
2873                         cur_len = line_len;
2874                 }
2875
2876                 /* we have encountered line break */
2877                 if (ch_len == 1 && *cbuf == '\n') {
2878                         gint clen;
2879                         gchar cb[CHAR_BUF_SIZE];
2880
2881                         /* should we join the next line */
2882                         if ((autowrap || i_len != cur_len) && do_delete &&
2883                         !is_sig_separator(compose, textbuf, cur_pos+i_len) &&
2884                             join_next_line_is_needed
2885                                 (textbuf, cur_pos + 1, tlen, i_len, autowrap)) {
2886                                 do_delete = TRUE;
2887                         } else
2888                                 do_delete = FALSE;
2889
2890                         /* skip delete if it is continuous URL */
2891                         if (do_delete && (line_pos - p_pos <= i_len) &&
2892                             gtkut_text_buffer_is_uri_string(textbuf, line_pos,
2893                                                             tlen))
2894                                 do_delete = FALSE;
2895
2896                         /* should we delete to perform smart wrapping */
2897                         if (line_len < linewrap_len && do_delete) {
2898                                 /* get rid of newline */
2899                                 gtk_text_buffer_get_iter_at_offset(textbuf,
2900                                                                    &iter,
2901                                                                    cur_pos);
2902                                 end_iter = iter;
2903                                 gtk_text_iter_forward_char(&end_iter);
2904                                 gtk_text_buffer_delete(textbuf, &iter, &end_iter);
2905                                 tlen--;
2906
2907                                 /* if text starts with quote fmt or with
2908                                    indent string, delete them */
2909                                 if (i_len) {
2910                                         guint ilen;
2911                                         ilen =  gtkut_text_buffer_str_compare_n
2912                                                 (textbuf, cur_pos, p_pos, i_len,
2913                                                  tlen);
2914                                         if (ilen) {
2915                                                 end_iter = iter;
2916                                                 gtk_text_iter_forward_chars
2917                                                         (&end_iter, ilen);
2918                                                 gtk_text_buffer_delete(textbuf,
2919                                                                        &iter,
2920                                                                        &end_iter);
2921                                                 tlen -= ilen;
2922                                         }
2923                                 }
2924
2925                                 gtk_text_buffer_get_iter_at_offset(textbuf,
2926                                                                    &iter,
2927                                                                    cur_pos);
2928                                 GET_CHAR(&iter, cb, clen);
2929
2930                                 /* insert space if it's alphanumeric */
2931                                 if ((cur_pos != line_pos) &&
2932                                     ((clen > 1) || isalnum((guchar)cb[0]))) {
2933                                         GtkTextIter cursor_iter;
2934                                         gboolean go_back = FALSE;
2935                                         gtk_text_buffer_get_iter_at_mark(textbuf, &cursor_iter, cursor_mark);
2936                                         if (gtk_text_iter_get_offset(&iter) ==
2937                                                  gtk_text_iter_get_offset(&cursor_iter))
2938                                                 go_back = TRUE;
2939                                         
2940                                         gtk_text_buffer_insert(textbuf, &iter,
2941                                                                " ", 1);
2942                                         if (go_back) {
2943                                                 gtk_text_buffer_get_iter_at_mark(textbuf, &cursor_iter, cursor_mark);
2944                                                 gtk_text_iter_backward_chars(&cursor_iter, 1);
2945                                                 gtk_text_buffer_place_cursor(textbuf, &cursor_iter);
2946                                         }
2947                                         tlen++;
2948                                 }
2949
2950                                 /* and start over with current line */
2951                                 cur_pos = p_pos - 1;
2952                                 line_pos = cur_pos;
2953                                 line_len = cur_len = 0;
2954                                 do_delete = FALSE;
2955                                 is_new_line = TRUE;
2956 #ifdef WRAP_DEBUG
2957                                 g_print("after delete l_pos=");
2958                                 dump_text(textbuf, line_pos, tlen, 1);
2959 #endif
2960                                 /* move beginning of line if we are on LF */
2961                                 gtk_text_buffer_get_iter_at_offset(textbuf,
2962                                                                    &iter,
2963                                                                    line_pos);
2964                                 GET_CHAR(&iter, cb, clen);
2965                                 if (clen == 1 && *cb == '\n')
2966                                         line_pos++;
2967 #ifdef WRAP_DEBUG
2968                                 g_print("new line_pos=%d\n", line_pos);
2969 #endif
2970
2971                                 continue;
2972                         }
2973
2974                         /* mark new line beginning */
2975                         line_pos = cur_pos + 1;
2976                         line_len = cur_len = 0;
2977                         do_delete = FALSE;
2978                         is_new_line = TRUE;
2979                         continue;
2980                 }
2981
2982                 if (ch_len < 0) {
2983                         cbuf[0] = '\0';
2984                         ch_len = 1;
2985                 }
2986
2987                 /* possible line break */
2988                 if (ch_len == 1 && isspace(*(guchar *)cbuf)) {
2989                         line_pos = cur_pos + 1;
2990                         line_len = cur_len + ch_len;
2991                 }
2992
2993                 /* are we over wrapping length set in preferences ? */
2994                 if (cur_len + DISP_WIDTH(ch_len) > linewrap_len) {
2995                         gint clen;
2996
2997 #ifdef WRAP_DEBUG
2998                         g_print("should wrap cur_pos=%d ", cur_pos);
2999                         dump_text(textbuf, p_pos, tlen, 1);
3000                         dump_text(textbuf, line_pos, tlen, 1);
3001 #endif
3002                         /* force wrapping if it is one long word but not URL */
3003                         if (line_pos - p_pos <= i_len)
3004                                 if (!gtkut_text_buffer_is_uri_string
3005                                     (textbuf, line_pos, tlen))
3006                                         line_pos = cur_pos - 1;
3007 #ifdef WRAP_DEBUG
3008                         g_print("new line_pos=%d\n", line_pos);
3009 #endif
3010
3011                         gtk_text_buffer_get_iter_at_offset(textbuf,
3012                                                            &iter,
3013                                                            line_pos - 1);
3014                         GET_CHAR(&iter, cbuf, clen);
3015
3016                         /* if next character is space delete it */
3017                         if (clen == 1 && isspace(*(guchar *)cbuf)) {
3018                                 if (p_pos + i_len != line_pos ||
3019                                     !gtkut_text_buffer_is_uri_string
3020                                         (textbuf, line_pos, tlen)) {
3021                                         /* workaround for correct cursor
3022                                            position */
3023                                         if (set_editable_pos == FALSE) {
3024                                                 GtkTextMark *ins = gtk_text_buffer_get_insert(textbuf);
3025                                                 gtk_text_buffer_get_iter_at_mark(textbuf, &iter, ins);
3026                                                 editable_pos = gtk_text_iter_get_offset(&iter);
3027                                                 if (editable_pos == line_pos)
3028                                                         set_editable_pos = TRUE;
3029                                         }
3030                                         gtk_text_buffer_get_iter_at_offset(textbuf,
3031                                                            &iter,
3032                                                            line_pos-1);
3033                                         gtk_text_buffer_get_iter_at_offset(textbuf,
3034                                                            &end_iter,
3035                                                            line_pos);
3036                                         gtk_text_buffer_delete(textbuf, &iter, &end_iter);
3037                                         //gtk_stext_set_point(text, line_pos);
3038                                         //gtk_stext_backward_delete(text, 1);
3039                                         tlen--;
3040                                         cur_pos--;
3041                                         line_pos--;
3042                                         cur_len--;
3043                                         line_len--;
3044                                 }
3045                         }
3046
3047                         /* if it is URL at beginning of line don't wrap */
3048                         if (p_pos + i_len == line_pos &&
3049                             gtkut_text_buffer_is_uri_string(textbuf, line_pos, tlen)) {
3050 #ifdef WRAP_DEBUG
3051                                 g_print("found URL at ");
3052                                 dump_text(textbuf, line_pos, tlen, 1);
3053 #endif
3054                                 continue;
3055                         }
3056
3057                         /* insert CR */
3058                         gtk_text_buffer_get_iter_at_offset(textbuf,
3059                                                            &iter,
3060                                                            line_pos);
3061                         gtk_text_buffer_insert(textbuf, &iter, "\n", 1);
3062                         //gtk_stext_set_point(text, line_pos);
3063                         //gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
3064                         //gtk_stext_compact_buffer(text);
3065                         tlen++;
3066                         line_pos++;
3067                         /* for loop will increase it */
3068                         cur_pos = line_pos - 1;
3069                         /* start over with current line */
3070                         is_new_line = TRUE;
3071                         line_len = cur_len = 0;
3072                         if (autowrap || i_len > 0) {
3073                                 do_delete = TRUE;
3074                         } else
3075                                 do_delete = FALSE;
3076 #ifdef WRAP_DEBUG
3077                         g_print("after CR insert ");
3078                         dump_text(textbuf, line_pos, tlen, 1);
3079                         dump_text(textbuf, cur_pos, tlen, 1);
3080 #endif
3081
3082                         /* should we insert quotation ? */
3083                         if (linewrap_quote && i_len) {
3084                                 /* only if line is not already quoted  */
3085                                 if (!gtkut_text_buffer_str_compare
3086                                         (textbuf, line_pos, tlen, qfmt)) {
3087                                         guint ins_len;
3088                                         
3089                                         gtk_text_buffer_get_iter_at_offset(textbuf, &iter, line_pos);
3090                                         
3091                                         if (line_pos - p_pos > i_len) {
3092                                                 ins_len = ins_quote
3093                                                         (textbuf, &iter, i_len, p_pos,
3094                                                          tlen, qfmt);
3095                                                 tlen += ins_len;
3096                                         }
3097 #ifdef WRAP_DEBUG
3098                                         g_print("after quote insert ");
3099                                         dump_text(textbuf, line_pos, tlen, 1);
3100 #endif
3101                                 }
3102                         }
3103                         continue;
3104                 }
3105
3106                 if (ch_len > 1) {
3107                         line_pos = cur_pos + 1;
3108                         line_len = cur_len + ch_len;
3109                 }
3110                 /* advance to next character in buffer */
3111                 cur_len += ch_len;
3112         }
3113
3114         if (set_editable_pos && editable_pos <= tlen) {
3115                 gtk_text_buffer_get_iter_at_offset(textbuf, &iter, editable_pos);
3116                 gtk_text_buffer_place_cursor(textbuf, &iter);
3117         }
3118 }
3119
3120 #undef GET_CHAR
3121 #undef CHAR_BUF_SIZE
3122
3123 static void compose_set_title(Compose *compose)
3124 {
3125         gchar *str;
3126         gchar *edited;
3127
3128         edited = compose->modified ? _(" [Edited]") : "";
3129         if (compose->account && compose->account->address)
3130                 str = g_strdup_printf(_("%s - Compose message%s"),
3131                                       compose->account->address, edited);
3132         else
3133                 str = g_strdup_printf(_("Compose message%s"), edited);
3134         gtk_window_set_title(GTK_WINDOW(compose->window), str);
3135         g_free(str);
3136 }
3137
3138 /**
3139  * compose_current_mail_account:
3140  * 
3141  * Find a current mail account (the currently selected account, or the
3142  * default account, if a news account is currently selected).  If a
3143  * mail account cannot be found, display an error message.
3144  * 
3145  * Return value: Mail account, or NULL if not found.
3146  **/
3147 static PrefsAccount *
3148 compose_current_mail_account(void)
3149 {
3150         PrefsAccount *ac;
3151
3152         if (cur_account && cur_account->protocol != A_NNTP)
3153                 ac = cur_account;
3154         else {
3155                 ac = account_get_default();
3156                 if (!ac || ac->protocol == A_NNTP) {
3157                         alertpanel_error(_("Account for sending mail is not specified.\n"
3158                                            "Please select a mail account before sending."));
3159                         return NULL;
3160                 }
3161         }
3162         return ac;
3163 }
3164
3165 static void compose_select_account(Compose *compose, PrefsAccount *account,
3166                                    gboolean init)
3167 {
3168         GtkItemFactory *ifactory;
3169
3170         g_return_if_fail(account != NULL);
3171
3172         compose->account = account;
3173
3174         compose_set_title(compose);
3175
3176         ifactory = gtk_item_factory_from_widget(compose->menubar);
3177 #if 0
3178         if (account->protocol == A_NNTP) {
3179                 gtk_widget_show(compose->newsgroups_hbox);
3180                 gtk_widget_show(compose->newsgroups_entry);
3181                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 4);
3182                 compose->use_newsgroups = TRUE;
3183
3184                 menu_set_active(ifactory, "/View/To", FALSE);
3185                 menu_set_sensitive(ifactory, "/View/To", TRUE);
3186                 menu_set_active(ifactory, "/View/Cc", FALSE);
3187                 menu_set_sensitive(ifactory, "/View/Cc", TRUE);
3188                 menu_set_sensitive(ifactory, "/View/Followup to", TRUE);
3189         } else {
3190                 gtk_widget_hide(compose->newsgroups_hbox);
3191                 gtk_widget_hide(compose->newsgroups_entry);
3192                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 0);
3193                 gtk_widget_queue_resize(compose->table_vbox);
3194                 compose->use_newsgroups = FALSE;
3195
3196                 menu_set_active(ifactory, "/View/To", TRUE);
3197                 menu_set_sensitive(ifactory, "/View/To", FALSE);
3198                 menu_set_active(ifactory, "/View/Cc", TRUE);
3199                 menu_set_sensitive(ifactory, "/View/Cc", FALSE);
3200                 menu_set_active(ifactory, "/View/Followup to", FALSE);
3201                 menu_set_sensitive(ifactory, "/View/Followup to", FALSE);
3202         }
3203
3204         if (account->set_autocc) {
3205                 compose_entry_show(compose, COMPOSE_ENTRY_CC);
3206                 if (account->auto_cc && compose->mode != COMPOSE_REEDIT)
3207                         compose_entry_set(compose, account->auto_cc,
3208                                           COMPOSE_ENTRY_CC);
3209         }
3210         if (account->set_autobcc) {
3211                 compose_entry_show(compose, COMPOSE_ENTRY_BCC);
3212                 if (account->auto_bcc && compose->mode != COMPOSE_REEDIT)
3213                         compose_entry_set(compose, account->auto_bcc,
3214                                           COMPOSE_ENTRY_BCC);
3215         }
3216         if (account->set_autoreplyto) {
3217                 compose_entry_show(compose, COMPOSE_ENTRY_REPLY_TO);
3218                 if (account->auto_replyto && compose->mode != COMPOSE_REEDIT)
3219                         compose_entry_set(compose, account->auto_replyto,
3220                                           COMPOSE_ENTRY_REPLY_TO);
3221         }
3222
3223 #endif
3224
3225         if (account->default_sign && compose->mode != COMPOSE_REDIRECT)
3226                 menu_set_active(ifactory, "/Options/Sign", TRUE);
3227         else
3228                 menu_set_active(ifactory, "/Options/Sign", FALSE);
3229         if (account->default_encrypt && compose->mode != COMPOSE_REDIRECT)
3230                 menu_set_active(ifactory, "/Options/Encrypt", TRUE);
3231         else
3232                 menu_set_active(ifactory, "/Options/Encrypt", FALSE);
3233                                        
3234         activate_privacy_system(compose, account);
3235
3236         if (!init && compose->mode != COMPOSE_REDIRECT)
3237                 compose_insert_sig(compose, TRUE);
3238 }
3239
3240 gboolean compose_check_for_valid_recipient(Compose *compose) {
3241         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
3242         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
3243         gboolean recipient_found = FALSE;
3244         GSList *list;
3245         gchar **strptr;
3246
3247         /* free to and newsgroup list */
3248         slist_free_strings(compose->to_list);
3249         g_slist_free(compose->to_list);
3250         compose->to_list = NULL;
3251                         
3252         slist_free_strings(compose->newsgroup_list);
3253         g_slist_free(compose->newsgroup_list);
3254         compose->newsgroup_list = NULL;
3255
3256         /* search header entries for to and newsgroup entries */
3257         for (list = compose->header_list; list; list = list->next) {
3258                 gchar *header;
3259                 gchar *entry;
3260                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3261                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3262                 g_strstrip(entry);
3263                 if (entry[0] != '\0') {
3264                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
3265                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3266                                         compose->to_list = address_list_append(compose->to_list, entry);
3267                                         recipient_found = TRUE;
3268                                 }
3269                         }
3270                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
3271                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3272                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
3273                                         recipient_found = TRUE;
3274                                 }
3275                         }
3276                 }
3277                 g_free(header);
3278                 g_free(entry);
3279         }
3280         return recipient_found;
3281 }
3282
3283 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
3284 {
3285         const gchar *str;
3286
3287         if (compose_check_for_valid_recipient(compose) == FALSE) {
3288                 alertpanel_error(_("Recipient is not specified."));
3289                 return FALSE;
3290         }
3291
3292         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3293         if (*str == '\0' && check_subject == TRUE) {
3294                 AlertValue aval;
3295
3296                 aval = alertpanel(_("Send"),
3297                                   _("Subject is empty. Send it anyway?"),
3298                                   GTK_STOCK_YES, GTK_STOCK_NO, NULL);
3299                 if (aval != G_ALERTDEFAULT)
3300                         return FALSE;
3301         }
3302
3303         return TRUE;
3304 }
3305
3306 gint compose_send(Compose *compose)
3307 {
3308         gint msgnum;
3309         FolderItem *folder;
3310         gint val = -1;
3311         gchar *msgpath;
3312
3313         compose_allow_user_actions (compose, FALSE);
3314         compose->sending = TRUE;
3315
3316         if (compose_check_entries(compose, TRUE) == FALSE)
3317                 goto bail;
3318
3319         val = compose_queue(compose, &msgnum, &folder);
3320
3321         if (val) {
3322                 alertpanel_error(_("Could not queue message for sending"));
3323                 goto bail;
3324         }
3325
3326
3327         if (prefs_common.send_dialog_mode != SEND_DIALOG_ALWAYS) {
3328                 compose->sending = FALSE;
3329                 compose_close(compose);
3330                 /* No more compose access in the normal codepath 
3331                  * after this point! */
3332         }
3333
3334         if (msgnum == 0) {
3335                 alertpanel_error(_("The message was queued but could not be "
3336                                    "sent.\nUse \"Send queued messages\" from "
3337                                    "the main window to retry."));
3338                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3339                         compose->sending = FALSE;
3340                         compose_allow_user_actions (compose, TRUE);
3341                 }
3342                 return 0;
3343         }
3344         
3345         msgpath = folder_item_fetch_msg(folder, msgnum);
3346         val = procmsg_send_message_queue(msgpath);
3347         g_free(msgpath);
3348
3349         if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3350                 compose->sending = FALSE;
3351                 compose_allow_user_actions (compose, TRUE);
3352                 if (val != 0) {
3353                         folder_item_remove_msg(folder, msgnum);
3354                         folder_item_scan(folder);
3355                 }
3356         }
3357
3358         if (val == 0) {
3359                 folder_item_remove_msg(folder, msgnum);
3360                 folder_item_scan(folder);
3361                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS)
3362                         compose_close(compose);
3363         } else {
3364                 alertpanel_error(_("The message was queued but could not be "
3365                                    "sent.\nUse \"Send queued messages\" from "
3366                                    "the main window to retry."));
3367                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3368                         compose_allow_user_actions (compose, TRUE);
3369                         compose->sending = FALSE;               
3370                 }
3371                 return -1;
3372         }
3373
3374         return 0;
3375
3376 bail:
3377         compose_allow_user_actions (compose, TRUE);
3378         compose->sending = FALSE;
3379
3380         return -1;
3381 }
3382
3383 static gboolean compose_use_attach(Compose *compose) 
3384 {
3385         GtkTreeModel *model = gtk_tree_view_get_model
3386                                 (GTK_TREE_VIEW(compose->attach_clist));
3387         return gtk_tree_model_iter_n_children(model, NULL) > 0;
3388 }
3389
3390 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3391                                                            FILE *fp)
3392 {
3393         gchar buf[BUFFSIZE];
3394         gchar *str;
3395         gboolean first_to_address;
3396         gboolean first_cc_address;
3397         GSList *list;
3398         ComposeHeaderEntry *headerentry;
3399         const gchar *headerentryname;
3400         gchar *cc_hdr;
3401         gchar *to_hdr;
3402
3403         debug_print("Writing redirect header\n");
3404
3405         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3406         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3407
3408         first_to_address = TRUE;
3409         first_cc_address = TRUE;
3410         for (list = compose->header_list; list; list = list->next) {
3411                 headerentry = ((ComposeHeaderEntry *)list->data);
3412                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3413
3414                 if (g_utf8_collate(headerentryname, cc_hdr) == 0 
3415                    || g_utf8_collate(headerentryname, to_hdr) == 0) {
3416                         const gchar *entstr = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3417                         Xstrdup_a(str, entstr, return -1);
3418                         g_strstrip(str);
3419                         if (str[0] != '\0') {
3420                                 compose_convert_header
3421                                         (buf, sizeof(buf), str,
3422                                         strlen("Resent-To") + 2, TRUE);
3423                                 if (g_utf8_collate(headerentryname, to_hdr) == 0) {
3424                                         if (first_to_address) {
3425                                                 fprintf(fp, "Resent-To: ");
3426                                                 first_to_address = FALSE;
3427                                         } else {
3428                                                 fprintf(fp, ",");
3429                                         }
3430                                 }
3431                                 if (g_utf8_collate(headerentryname, cc_hdr) == 0) {
3432                                         if (first_cc_address) {
3433                                                 fprintf(fp, "\n");
3434                                                 fprintf(fp, "Resent-Cc: ");
3435                                                 first_cc_address = FALSE;
3436                                         } else {
3437                                                 fprintf(fp, ",");
3438                                         }
3439                                 }
3440                                 
3441                                 fprintf(fp, "%s", buf);
3442                         }
3443                 }
3444         }
3445         /* if (!first_address) { */
3446         fprintf(fp, "\n");
3447         /* } */
3448
3449         return(0);
3450 }
3451
3452 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3453 {
3454         gchar buf[BUFFSIZE];
3455         gchar *str;
3456         const gchar *entstr;
3457         /* struct utsname utsbuf; */
3458
3459         g_return_val_if_fail(fp != NULL, -1);
3460         g_return_val_if_fail(compose->account != NULL, -1);
3461         g_return_val_if_fail(compose->account->address != NULL, -1);
3462
3463         /* Resent-Date */
3464         get_rfc822_date(buf, sizeof(buf));
3465         fprintf(fp, "Resent-Date: %s\n", buf);
3466
3467         /* Resent-From */
3468         if (compose->account->name && *compose->account->name) {
3469                 compose_convert_header
3470                         (buf, sizeof(buf), compose->account->name,
3471                          strlen("From: "), TRUE);
3472                 fprintf(fp, "Resent-From: %s <%s>\n",
3473                         buf, compose->account->address);
3474         } else
3475                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3476
3477         /* Subject */
3478         entstr = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3479         if (*entstr != '\0') {
3480                 Xstrdup_a(str, entstr, return -1);
3481                 g_strstrip(str);
3482                 if (*str != '\0') {
3483                         compose_convert_header(buf, sizeof(buf), str,
3484                                                strlen("Subject: "), FALSE);
3485                         fprintf(fp, "Subject: %s\n", buf);
3486                 }
3487         }
3488
3489         /* Resent-Message-ID */
3490         if (compose->account->gen_msgid) {
3491                 generate_msgid(buf, sizeof(buf));
3492                 fprintf(fp, "Resent-Message-ID: <%s>\n", buf);
3493                 compose->msgid = g_strdup(buf);
3494         }
3495
3496         compose_redirect_write_headers_from_headerlist(compose, fp);
3497
3498         /* separator between header and body */
3499         fputs("\n", fp);
3500
3501         return 0;
3502 }
3503
3504 static gint compose_redirect_write_to_file(Compose *compose, FILE *fdest)
3505 {
3506         FILE *fp;
3507         size_t len;
3508         gchar buf[BUFFSIZE];
3509
3510         if ((fp = fopen(compose->redirect_filename, "rb")) == NULL) {
3511                 FILE_OP_ERROR(compose->redirect_filename, "fopen");
3512                 return -1;
3513         }
3514
3515         while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
3516                 /* should filter returnpath, delivered-to */
3517                 if (g_ascii_strncasecmp(buf, "Return-Path:",
3518                                         strlen("Return-Path:")) == 0 ||
3519                     g_ascii_strncasecmp(buf, "Delivered-To:",
3520                                         strlen("Delivered-To:")) == 0 ||
3521                     g_ascii_strncasecmp(buf, "Received:",
3522                                         strlen("Received:")) == 0 ||
3523                     g_ascii_strncasecmp(buf, "Subject:",
3524                                         strlen("Subject:")) == 0 ||
3525                     g_ascii_strncasecmp(buf, "X-UIDL:",
3526                                         strlen("X-UIDL:")) == 0)
3527                         continue;
3528
3529                 if (fputs(buf, fdest) == -1)
3530                         goto error;
3531
3532                 if (!prefs_common.redirect_keep_from) {
3533                         if (g_ascii_strncasecmp(buf, "From:",
3534                                           strlen("From:")) == 0) {
3535                                 fputs(" (by way of ", fdest);
3536                                 if (compose->account->name
3537                                     && *compose->account->name) {
3538                                         compose_convert_header
3539                                                 (buf, sizeof(buf),
3540                                                  compose->account->name,
3541                                                  strlen("From: "),
3542                                                  FALSE);
3543                                         fprintf(fdest, "%s <%s>",
3544                                                 buf,
3545                                                 compose->account->address);
3546                                 } else
3547                                         fprintf(fdest, "%s",
3548                                                 compose->account->address);
3549                                 fputs(")", fdest);
3550                         }
3551                 }
3552
3553                 if (fputs("\n", fdest) == -1)
3554                         goto error;
3555         }
3556
3557         compose_redirect_write_headers(compose, fdest);
3558
3559         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3560                 if (fwrite(buf, sizeof(gchar), len, fdest) != len)
3561                         goto error;
3562         }
3563
3564         fclose(fp);
3565
3566         return 0;
3567 error:
3568         fclose(fp);
3569
3570         return -1;
3571 }
3572
3573 static gint compose_write_to_file(Compose *compose, FILE *fp, gint action)
3574 {
3575         GtkTextBuffer *buffer;
3576         GtkTextIter start, end;
3577         gchar *chars;
3578         gchar *buf;
3579         const gchar *out_codeset;
3580         EncodingType encoding;
3581         MimeInfo *mimemsg, *mimetext;
3582
3583         /* create message MimeInfo */
3584         mimemsg = procmime_mimeinfo_new();
3585         mimemsg->type = MIMETYPE_MESSAGE;
3586         mimemsg->subtype = g_strdup("rfc822");
3587         mimemsg->content = MIMECONTENT_MEM;
3588         mimemsg->data.mem = compose_get_header(compose);
3589
3590         /* Create text part MimeInfo */
3591         /* get all composed text */
3592         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
3593         gtk_text_buffer_get_start_iter(buffer, &start);
3594         gtk_text_buffer_get_end_iter(buffer, &end);
3595         chars = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
3596         if (is_ascii_str(chars)) {
3597                 buf = chars;
3598                 chars = NULL;
3599                 out_codeset = CS_US_ASCII;
3600                 encoding = ENC_7BIT;
3601         } else {
3602                 const gchar *src_codeset;
3603
3604                 out_codeset = conv_get_outgoing_charset_str();
3605                 if (!g_ascii_strcasecmp(out_codeset, CS_US_ASCII))
3606                         out_codeset = CS_ISO_8859_1;
3607
3608                 if (prefs_common.encoding_method == CTE_BASE64)
3609                         encoding = ENC_BASE64;
3610                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
3611                         encoding = ENC_QUOTED_PRINTABLE;
3612                 else if (prefs_common.encoding_method == CTE_8BIT)
3613                         encoding = ENC_8BIT;
3614                 else
3615                         encoding = procmime_get_encoding_for_charset(out_codeset);
3616
3617                 src_codeset = CS_INTERNAL;
3618                 /* if current encoding is US-ASCII, set it the same as
3619                    outgoing one to prevent code conversion failure */
3620                 if (!g_ascii_strcasecmp(src_codeset, CS_US_ASCII))
3621                         src_codeset = out_codeset;
3622
3623                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
3624                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
3625
3626                 if (action == COMPOSE_WRITE_FOR_SEND) {
3627                         buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
3628                         if (!buf) {
3629                                 AlertValue aval;
3630                                 gchar *msg;
3631
3632                                 msg = g_strdup_printf(_("Can't convert the character encoding of the message from\n"
3633                                                         "%s to %s.\n"
3634                                                         "Send it anyway?"), src_codeset, out_codeset);
3635                                 aval = alertpanel_with_type
3636                                         (_("Error"), msg, _("Yes"), _("+No"), NULL, NULL, ALERT_ERROR);
3637                                 g_free(msg);
3638
3639                                 if (aval != G_ALERTDEFAULT) {
3640                                         g_free(chars);
3641                                         return -1;
3642                                 } else {
3643                                         buf = chars;
3644                                         out_codeset = src_codeset;
3645                                         chars = NULL;
3646                                 }
3647                         }
3648                 } else {
3649                         buf = chars;
3650                         out_codeset = src_codeset;
3651                         chars = NULL;
3652                 }
3653         }
3654         g_free(chars);
3655
3656         mimetext = procmime_mimeinfo_new();
3657         mimetext->content = MIMECONTENT_MEM;
3658         mimetext->data.mem = buf;
3659         mimetext->type = MIMETYPE_TEXT;
3660         mimetext->subtype = g_strdup("plain");
3661         g_hash_table_insert(mimetext->typeparameters, g_strdup("charset"),
3662                             g_strdup(out_codeset));
3663         /* protect trailing spaces when signing message */
3664         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing &&