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