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