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