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