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