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