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