2006-01-18 [paul] 1.9.100cvs168
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #ifndef PANGO_ENABLE_ENGINE
27 #  define PANGO_ENABLE_ENGINE
28 #endif
29
30 #include <glib.h>
31 #include <glib/gi18n.h>
32 #include <gdk/gdkkeysyms.h>
33 #include <gtk/gtkmain.h>
34 #include <gtk/gtkmenu.h>
35 #include <gtk/gtkmenuitem.h>
36 #include <gtk/gtkitemfactory.h>
37 #include <gtk/gtkcheckmenuitem.h>
38 #include <gtk/gtkoptionmenu.h>
39 #include <gtk/gtkwidget.h>
40 #include <gtk/gtkvpaned.h>
41 #include <gtk/gtkentry.h>
42 #include <gtk/gtkeditable.h>
43 #include <gtk/gtkwindow.h>
44 #include <gtk/gtksignal.h>
45 #include <gtk/gtkvbox.h>
46 #include <gtk/gtkcontainer.h>
47 #include <gtk/gtkhandlebox.h>
48 #include <gtk/gtktoolbar.h>
49 #include <gtk/gtktable.h>
50 #include <gtk/gtkhbox.h>
51 #include <gtk/gtklabel.h>
52 #include <gtk/gtkscrolledwindow.h>
53 #include <gtk/gtktreeview.h>
54 #include <gtk/gtkliststore.h>
55 #include <gtk/gtktreeselection.h>
56 #include <gtk/gtktreemodel.h>
57
58 #include <gtk/gtkdnd.h>
59 #include <gtk/gtkclipboard.h>
60 #include <pango/pango-break.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <ctype.h>
65 #include <sys/types.h>
66 #include <sys/stat.h>
67 #include <unistd.h>
68 #include <time.h>
69 #include <stdlib.h>
70 #if HAVE_SYS_WAIT_H
71 #  include <sys/wait.h>
72 #endif
73 #include <signal.h>
74 #include <errno.h>
75 #ifndef G_OS_WIN32  /* fixme we should have a configure test. */
76 #include <libgen.h>
77 #endif
78
79 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
80 #  include <wchar.h>
81 #  include <wctype.h>
82 #endif
83
84 #include "sylpheed.h"
85 #include "main.h"
86 #include "mainwindow.h"
87 #include "compose.h"
88 #include "addressbook.h"
89 #include "folderview.h"
90 #include "procmsg.h"
91 #include "menu.h"
92 #include "stock_pixmap.h"
93 #include "send_message.h"
94 #include "imap.h"
95 #include "news.h"
96 #include "customheader.h"
97 #include "prefs_common.h"
98 #include "prefs_account.h"
99 #include "action.h"
100 #include "account.h"
101 #include "filesel.h"
102 #include "procheader.h"
103 #include "procmime.h"
104 #include "statusbar.h"
105 #include "about.h"
106 #include "base64.h"
107 #include "quoted-printable.h"
108 #include "codeconv.h"
109 #include "utils.h"
110 #include "gtkutils.h"
111 #include "socket.h"
112 #include "alertpanel.h"
113 #include "manage_window.h"
114 #include "gtkshruler.h"
115 #include "folder.h"
116 #include "addr_compl.h"
117 #include "quote_fmt.h"
118 #include "template.h"
119 #include "undo.h"
120 #include "foldersel.h"
121 #include "toolbar.h"
122 #include "inc.h"
123 enum
124 {
125         COL_MIMETYPE = 0,
126         COL_SIZE     = 1,
127         COL_NAME     = 2,
128         COL_DATA     = 3,
129         COL_AUTODATA = 4,
130         N_COL_COLUMNS
131 };
132
133 #define N_ATTACH_COLS   (N_COL_COLUMNS)
134
135 typedef enum
136 {
137         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
138         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
139         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
140         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
141         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
142         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
143         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
144         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
145         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
146         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
147         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
148         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
149         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
150         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
151         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END
152 } ComposeCallAdvancedAction;
153
154 typedef enum
155 {
156         PRIORITY_HIGHEST = 1,
157         PRIORITY_HIGH,
158         PRIORITY_NORMAL,
159         PRIORITY_LOW,
160         PRIORITY_LOWEST
161 } PriorityLevel;
162
163 typedef enum
164 {
165         COMPOSE_INSERT_SUCCESS,
166         COMPOSE_INSERT_READ_ERROR,
167         COMPOSE_INSERT_INVALID_CHARACTER,
168         COMPOSE_INSERT_NO_FILE
169 } ComposeInsertResult;
170
171 typedef enum
172 {
173         COMPOSE_QUIT_EDITING,
174         COMPOSE_KEEP_EDITING,
175         COMPOSE_AUTO_SAVE
176 } ComposeDraftAction;
177
178 typedef enum
179 {
180         COMPOSE_WRITE_FOR_SEND,
181         COMPOSE_WRITE_FOR_STORE
182 } ComposeWriteType;
183
184 #define B64_LINE_SIZE           57
185 #define B64_BUFFSIZE            77
186
187 #define MAX_REFERENCES_LEN      999
188
189 static GList *compose_list = NULL;
190
191 Compose *compose_generic_new                    (PrefsAccount   *account,
192                                                  const gchar    *to,
193                                                  FolderItem     *item,
194                                                  GPtrArray      *attach_files,
195                                                  GList          *listAddress );
196
197 static Compose *compose_create                  (PrefsAccount   *account,
198                                                  ComposeMode     mode);
199
200 static GtkWidget *compose_account_option_menu_create
201                                                 (Compose        *compose);
202 static void compose_set_out_encoding            (Compose        *compose);
203 static void compose_set_template_menu           (Compose        *compose);
204 static void compose_template_apply              (Compose        *compose,
205                                                  Template       *tmpl,
206                                                  gboolean        replace);
207 static void compose_destroy                     (Compose        *compose);
208
209 static void compose_entries_set                 (Compose        *compose,
210                                                  const gchar    *mailto);
211 static gint compose_parse_header                (Compose        *compose,
212                                                  MsgInfo        *msginfo);
213 static gchar *compose_parse_references          (const gchar    *ref,
214                                                  const gchar    *msgid);
215
216 static gchar *compose_quote_fmt                 (Compose        *compose,
217                                                  MsgInfo        *msginfo,
218                                                  const gchar    *fmt,
219                                                  const gchar    *qmark,
220                                                  const gchar    *body,
221                                                  gboolean        rewrap);
222
223 static void compose_reply_set_entry             (Compose        *compose,
224                                                  MsgInfo        *msginfo,
225                                                  gboolean        to_all,
226                                                  gboolean        to_ml,
227                                                  gboolean        to_sender,
228                                                  gboolean
229                                                  followup_and_reply_to);
230 static void compose_reedit_set_entry            (Compose        *compose,
231                                                  MsgInfo        *msginfo);
232
233 static void compose_insert_sig                  (Compose        *compose,
234                                                  gboolean        replace);
235 static gchar *compose_get_signature_str         (Compose        *compose);
236 static ComposeInsertResult compose_insert_file  (Compose        *compose,
237                                                  const gchar    *file);
238
239 static void compose_attach_append               (Compose        *compose,
240                                                  const gchar    *file,
241                                                  const gchar    *type,
242                                                  const gchar    *content_type);
243 static void compose_attach_parts                (Compose        *compose,
244                                                  MsgInfo        *msginfo);
245
246 static void compose_beautify_paragraph          (Compose        *compose,
247                                                  GtkTextIter    *par_iter,
248                                                  gboolean        force);
249 static void compose_wrap_all                    (Compose        *compose);
250 static void compose_wrap_all_full               (Compose        *compose,
251                                                  gboolean        autowrap);
252
253 static void compose_set_title                   (Compose        *compose);
254 static void compose_select_account              (Compose        *compose,
255                                                  PrefsAccount   *account,
256                                                  gboolean        init);
257
258 static PrefsAccount *compose_current_mail_account(void);
259 /* static gint compose_send                     (Compose        *compose); */
260 static gboolean compose_check_for_valid_recipient
261                                                 (Compose        *compose);
262 static gboolean compose_check_entries           (Compose        *compose,
263                                                  gboolean       check_subject);
264 static gint compose_write_to_file               (Compose        *compose,
265                                                  FILE           *fp,
266                                                  gint            action);
267 static gint compose_write_body_to_file          (Compose        *compose,
268                                                  const gchar    *file);
269 static gint compose_remove_reedit_target        (Compose        *compose,
270                                                  gboolean        force);
271 void compose_remove_draft                       (Compose        *compose);
272 static gint compose_queue                       (Compose        *compose,
273                                                  gint           *msgnum,
274                                                  FolderItem     **item);
275 static gint compose_queue_sub                   (Compose        *compose,
276                                                  gint           *msgnum,
277                                                  FolderItem     **item,
278                                                  gboolean       check_subject);
279 static void compose_add_attachments             (Compose        *compose,
280                                                  MimeInfo       *parent);
281 static gchar *compose_get_header                (Compose        *compose);
282
283 static void compose_convert_header              (Compose        *compose,
284                                                  gchar          *dest,
285                                                  gint            len,
286                                                  gchar          *src,
287                                                  gint            header_len,
288                                                  gboolean        addr_field);
289
290 static void compose_attach_info_free            (AttachInfo     *ainfo);
291 static void compose_attach_remove_selected      (Compose        *compose);
292
293 static void compose_attach_property             (Compose        *compose);
294 static void compose_attach_property_create      (gboolean       *cancelled);
295 static void attach_property_ok                  (GtkWidget      *widget,
296                                                  gboolean       *cancelled);
297 static void attach_property_cancel              (GtkWidget      *widget,
298                                                  gboolean       *cancelled);
299 static gint attach_property_delete_event        (GtkWidget      *widget,
300                                                  GdkEventAny    *event,
301                                                  gboolean       *cancelled);
302 static gboolean attach_property_key_pressed     (GtkWidget      *widget,
303                                                  GdkEventKey    *event,
304                                                  gboolean       *cancelled);
305
306 static void compose_exec_ext_editor             (Compose        *compose);
307 #ifdef G_OS_UNIX
308 static gint compose_exec_ext_editor_real        (const gchar    *file);
309 static gboolean compose_ext_editor_kill         (Compose        *compose);
310 static gboolean compose_input_cb                (GIOChannel     *source,
311                                                  GIOCondition    condition,
312                                                  gpointer        data);
313 static void compose_set_ext_editor_sensitive    (Compose        *compose,
314                                                  gboolean        sensitive);
315 #endif /* G_OS_UNIX */
316
317 static void compose_undo_state_changed          (UndoMain       *undostruct,
318                                                  gint            undo_state,
319                                                  gint            redo_state,
320                                                  gpointer        data);
321
322 static void compose_create_header_entry (Compose *compose);
323 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
324 static void compose_update_priority_menu_item(Compose * compose);
325
326 static void compose_add_field_list      ( Compose *compose,
327                                           GList *listAddress );
328
329 /* callback functions */
330
331 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
332                                          GtkAllocation  *allocation,
333                                          GtkSHRuler     *shruler);
334 static void account_activated           (GtkMenuItem    *menuitem,
335                                          gpointer        data);
336 static void attach_selected             (GtkTreeView    *tree_view, 
337                                          GtkTreePath    *tree_path,
338                                          GtkTreeViewColumn *column, 
339                                          Compose *compose);
340 static gboolean attach_button_pressed   (GtkWidget      *widget,
341                                          GdkEventButton *event,
342                                          gpointer        data);
343 static gboolean attach_key_pressed      (GtkWidget      *widget,
344                                          GdkEventKey    *event,
345                                          gpointer        data);
346
347 static void compose_send_cb             (gpointer        data,
348                                          guint           action,
349                                          GtkWidget      *widget);
350 static void compose_send_later_cb       (gpointer        data,
351                                          guint           action,
352                                          GtkWidget      *widget);
353
354 static void compose_draft_cb            (gpointer        data,
355                                          guint           action,
356                                          GtkWidget      *widget);
357
358 static void compose_attach_cb           (gpointer        data,
359                                          guint           action,
360                                          GtkWidget      *widget);
361 static void compose_insert_file_cb      (gpointer        data,
362                                          guint           action,
363                                          GtkWidget      *widget);
364 static void compose_insert_sig_cb       (gpointer        data,
365                                          guint           action,
366                                          GtkWidget      *widget);
367
368 static void compose_close_cb            (gpointer        data,
369                                          guint           action,
370                                          GtkWidget      *widget);
371
372 static void compose_set_encoding_cb     (gpointer        data,
373                                          guint           action,
374                                          GtkWidget      *widget);
375
376 static void compose_address_cb          (gpointer        data,
377                                          guint           action,
378                                          GtkWidget      *widget);
379 static void compose_template_activate_cb(GtkWidget      *widget,
380                                          gpointer        data);
381
382 static void compose_ext_editor_cb       (gpointer        data,
383                                          guint           action,
384                                          GtkWidget      *widget);
385
386 static gint compose_delete_cb           (GtkWidget      *widget,
387                                          GdkEventAny    *event,
388                                          gpointer        data);
389
390 static void compose_undo_cb             (Compose        *compose);
391 static void compose_redo_cb             (Compose        *compose);
392 static void compose_cut_cb              (Compose        *compose);
393 static void compose_copy_cb             (Compose        *compose);
394 static void compose_paste_cb            (Compose        *compose);
395 static void compose_paste_as_quote_cb   (Compose        *compose);
396 static void compose_paste_no_wrap_cb    (Compose        *compose);
397 static void compose_paste_wrap_cb       (Compose        *compose);
398 static void compose_allsel_cb           (Compose        *compose);
399
400 static void compose_advanced_action_cb  (Compose                   *compose,
401                                          ComposeCallAdvancedAction  action);
402
403 static void compose_grab_focus_cb       (GtkWidget      *widget,
404                                          Compose        *compose);
405
406 static void compose_changed_cb          (GtkTextBuffer  *textbuf,
407                                          Compose        *compose);
408
409 static void compose_wrap_cb             (gpointer        data,
410                                          guint           action,
411                                          GtkWidget      *widget);
412 static void compose_toggle_autowrap_cb  (gpointer        data,
413                                          guint           action,
414                                          GtkWidget      *widget);
415
416 static void compose_toggle_ruler_cb     (gpointer        data,
417                                          guint           action,
418                                          GtkWidget      *widget);
419 static void compose_toggle_sign_cb      (gpointer        data,
420                                          guint           action,
421                                          GtkWidget      *widget);
422 static void compose_toggle_encrypt_cb   (gpointer        data,
423                                          guint           action,
424                                          GtkWidget      *widget);
425 static void compose_set_privacy_system_cb(GtkWidget      *widget,
426                                           gpointer        data);
427 static void compose_update_privacy_system_menu_item(Compose * compose, gboolean warn);
428 static void activate_privacy_system     (Compose *compose, 
429                                          PrefsAccount *account,
430                                          gboolean warn);
431 static void compose_use_signing(Compose *compose, gboolean use_signing);
432 static void compose_use_encryption(Compose *compose, gboolean use_encryption);
433 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
434                                              GtkWidget *widget);
435 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
436                                              GtkWidget *widget);
437 static void compose_set_priority_cb     (gpointer        data,
438                                          guint           action,
439                                          GtkWidget      *widget);
440
441 static void compose_attach_drag_received_cb (GtkWidget          *widget,
442                                              GdkDragContext     *drag_context,
443                                              gint                x,
444                                              gint                y,
445                                              GtkSelectionData   *data,
446                                              guint               info,
447                                              guint               time,
448                                              gpointer            user_data);
449 static void compose_insert_drag_received_cb (GtkWidget          *widget,
450                                              GdkDragContext     *drag_context,
451                                              gint                x,
452                                              gint                y,
453                                              GtkSelectionData   *data,
454                                              guint               info,
455                                              guint               time,
456                                              gpointer            user_data);
457 static void compose_header_drag_received_cb (GtkWidget          *widget,
458                                              GdkDragContext     *drag_context,
459                                              gint                x,
460                                              gint                y,
461                                              GtkSelectionData   *data,
462                                              guint               info,
463                                              guint               time,
464                                              gpointer            user_data);
465
466 static gboolean compose_drag_drop           (GtkWidget *widget,
467                                              GdkDragContext *drag_context,
468                                              gint x, gint y,
469                                              guint time, gpointer user_data);
470
471 static void text_inserted               (GtkTextBuffer  *buffer,
472                                          GtkTextIter    *iter,
473                                          const gchar    *text,
474                                          gint            len,
475                                          Compose        *compose);
476 static Compose *compose_generic_reply(MsgInfo *msginfo, gboolean quote,
477                                   gboolean to_all, gboolean to_ml,
478                                   gboolean to_sender,
479                                   gboolean followup_and_reply_to,
480                                   const gchar *body);
481
482 gboolean compose_headerentry_changed_cb    (GtkWidget          *entry,
483                                             ComposeHeaderEntry *headerentry);
484 gboolean compose_headerentry_key_press_event_cb(GtkWidget              *entry,
485                                             GdkEventKey        *event,
486                                             ComposeHeaderEntry *headerentry);
487
488 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
489
490 static void compose_allow_user_actions (Compose *compose, gboolean allow);
491
492 #if USE_ASPELL
493 static void compose_check_all              (Compose *compose);
494 static void compose_highlight_all          (Compose *compose);
495 static void compose_check_backwards        (Compose *compose);
496 static void compose_check_forwards_go      (Compose *compose);
497 #endif
498
499 static gint compose_defer_auto_save_draft       (Compose        *compose);
500 static PrefsAccount *compose_guess_forward_account_from_msginfo (MsgInfo *msginfo);
501
502 static gboolean compose_close   (Compose *compose);
503
504 static GtkItemFactoryEntry compose_popup_entries[] =
505 {
506         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
507         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
508         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
509         {N_("/_Properties..."), NULL, compose_attach_property, 0, NULL}
510 };
511
512 static GtkItemFactoryEntry compose_entries[] =
513 {
514         {N_("/_Message"),                               NULL, NULL, 0, "<Branch>"},
515         {N_("/_Message/_Send"),         "<control>Return",
516                                         compose_send_cb, 0, NULL},
517         {N_("/_Message/Send _later"),   "<shift><control>S",
518                                         compose_send_later_cb,  0, NULL},
519         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
520         {N_("/_Message/_Attach file"),          "<control>M", compose_attach_cb,      0, NULL},
521         {N_("/_Message/_Insert file"),          "<control>I", compose_insert_file_cb, 0, NULL},
522         {N_("/_Message/Insert si_gnature"),     "<control>G", compose_insert_sig_cb,  0, NULL},
523         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
524         {N_("/_Message/_Save"),
525                                                 "<control>S", compose_draft_cb, COMPOSE_KEEP_EDITING, NULL},
526         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
527         {N_("/_Message/_Close"),                        "<control>W", compose_close_cb, 0, NULL},
528
529         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
530         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
531         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
532         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
533         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
534         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
535         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
536         {N_("/_Edit/Special paste"),    NULL, NULL, 0, "<Branch>"},
537         {N_("/_Edit/Special paste/as _quotation"),
538                                         NULL, compose_paste_as_quote_cb, 0, NULL},
539         {N_("/_Edit/Special paste/_wrapped"),
540                                         NULL, compose_paste_wrap_cb, 0, NULL},
541         {N_("/_Edit/Special paste/_unwrapped"),
542                                         NULL, compose_paste_no_wrap_cb, 0, NULL},
543         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
544         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
545         {N_("/_Edit/A_dvanced/Move a character backward"),
546                                         "<control>B",
547                                         compose_advanced_action_cb,
548                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
549                                         NULL},
550         {N_("/_Edit/A_dvanced/Move a character forward"),
551                                         "<control>F",
552                                         compose_advanced_action_cb,
553                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
554                                         NULL},
555         {N_("/_Edit/A_dvanced/Move a word backward"),
556                                         NULL, /* "<alt>B" */
557                                         compose_advanced_action_cb,
558                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
559                                         NULL},
560         {N_("/_Edit/A_dvanced/Move a word forward"),
561                                         NULL, /* "<alt>F" */
562                                         compose_advanced_action_cb,
563                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
564                                         NULL},
565         {N_("/_Edit/A_dvanced/Move to beginning of line"),
566                                         NULL, /* "<control>A" */
567                                         compose_advanced_action_cb,
568                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
569                                         NULL},
570         {N_("/_Edit/A_dvanced/Move to end of line"),
571                                         "<control>E",
572                                         compose_advanced_action_cb,
573                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
574                                         NULL},
575         {N_("/_Edit/A_dvanced/Move to previous line"),
576                                         "<control>P",
577                                         compose_advanced_action_cb,
578                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
579                                         NULL},
580         {N_("/_Edit/A_dvanced/Move to next line"),
581                                         "<control>N",
582                                         compose_advanced_action_cb,
583                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
584                                         NULL},
585         {N_("/_Edit/A_dvanced/Delete a character backward"),
586                                         "<control>H",
587                                         compose_advanced_action_cb,
588                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
589                                         NULL},
590         {N_("/_Edit/A_dvanced/Delete a character forward"),
591                                         "<control>D",
592                                         compose_advanced_action_cb,
593                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
594                                         NULL},
595         {N_("/_Edit/A_dvanced/Delete a word backward"),
596                                         NULL, /* "<control>W" */
597                                         compose_advanced_action_cb,
598                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
599                                         NULL},
600         {N_("/_Edit/A_dvanced/Delete a word forward"),
601                                         NULL, /* "<alt>D", */
602                                         compose_advanced_action_cb,
603                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
604                                         NULL},
605         {N_("/_Edit/A_dvanced/Delete line"),
606                                         "<control>U",
607                                         compose_advanced_action_cb,
608                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
609                                         NULL},
610         {N_("/_Edit/A_dvanced/Delete entire line"),
611                                         NULL,
612                                         compose_advanced_action_cb,
613                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
614                                         NULL},
615         {N_("/_Edit/A_dvanced/Delete to end of line"),
616                                         "<control>K",
617                                         compose_advanced_action_cb,
618                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END,
619                                         NULL},
620         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
621         {N_("/_Edit/_Wrap current paragraph"),
622                                         "<control>L", compose_wrap_cb, 0, NULL},
623         {N_("/_Edit/Wrap all long _lines"),
624                                         "<control><alt>L", compose_wrap_cb, 1, NULL},
625         {N_("/_Edit/Aut_o wrapping"),   "<shift><control>L", compose_toggle_autowrap_cb, 0, "<ToggleItem>"},
626         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
627         {N_("/_Edit/Edit with e_xternal editor"),
628                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
629 #if USE_ASPELL
630         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
631         {N_("/_Spelling/_Check all or check selection"),
632                                         NULL, compose_check_all, 0, NULL},
633         {N_("/_Spelling/_Highlight all misspelled words"),
634                                         NULL, compose_highlight_all, 0, NULL},
635         {N_("/_Spelling/Check _backwards misspelled word"),
636                                         NULL, compose_check_backwards , 0, NULL},
637         {N_("/_Spelling/_Forward to next misspelled word"),
638                                         NULL, compose_check_forwards_go, 0, NULL},
639 #endif
640         {N_("/_Options"),               NULL, NULL, 0, "<Branch>"},
641         {N_("/_Options/Privacy System"),                NULL, NULL,   0, "<Branch>"},
642         {N_("/_Options/Privacy System/None"),   NULL, NULL,   0, "<RadioItem>"},
643         {N_("/_Options/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
644         {N_("/_Options/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
645         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
646         {N_("/_Options/_Priority"),     NULL,           NULL,   0, "<Branch>"},
647         {N_("/_Options/Priority/_Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
648         {N_("/_Options/Priority/Hi_gh"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Options/Priority/Highest"},
649         {N_("/_Options/Priority/_Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Options/Priority/Highest"},
650         {N_("/_Options/Priority/Lo_w"),    NULL, compose_set_priority_cb, PRIORITY_LOW, "/Options/Priority/Highest"},
651         {N_("/_Options/Priority/_Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Options/Priority/Highest"},
652         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
653         {N_("/_Options/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
654         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
655         {N_("/_Options/Remo_ve references"),    NULL, compose_toggle_remove_refs_cb, 0, "<ToggleItem>"},
656         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
657
658 #define ENC_ACTION(action) \
659         NULL, compose_set_encoding_cb, action, \
660         "/Options/Character encoding/Automatic"
661
662         {N_("/_Options/Character _encoding"), NULL, NULL, 0, "<Branch>"},
663         {N_("/_Options/Character _encoding/_Automatic"),
664                         NULL, compose_set_encoding_cb, C_AUTO, "<RadioItem>"},
665         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
666
667         {N_("/_Options/Character _encoding/7bit ascii (US-ASC_II)"),
668          ENC_ACTION(C_US_ASCII)},
669         {N_("/_Options/Character _encoding/Unicode (_UTF-8)"),
670          ENC_ACTION(C_UTF_8)},
671         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
672
673         {N_("/_Options/Character _encoding/Western European (ISO-8859-_1)"),
674          ENC_ACTION(C_ISO_8859_1)},
675         {N_("/_Options/Character _encoding/Western European (ISO-8859-15)"),
676          ENC_ACTION(C_ISO_8859_15)},
677         {N_("/_Options/Character _encoding/Western European (Windows-1252)"),
678          ENC_ACTION(C_WINDOWS_1252)},
679         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
680
681         {N_("/_Options/Character _encoding/Central European (ISO-8859-_2)"),
682          ENC_ACTION(C_ISO_8859_2)},
683         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
684
685         {N_("/_Options/Character _encoding/_Baltic (ISO-8859-13)"),
686          ENC_ACTION(C_ISO_8859_13)},
687         {N_("/_Options/Character _encoding/Baltic (ISO-8859-_4)"),
688          ENC_ACTION(C_ISO_8859_4)},
689         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
690
691         {N_("/_Options/Character _encoding/Greek (ISO-8859-_7)"),
692          ENC_ACTION(C_ISO_8859_7)},
693         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
694
695         {N_("/_Options/Character _encoding/Hebrew (ISO-8859-_8)"),
696          ENC_ACTION(C_ISO_8859_8)},
697         {N_("/_Options/Character _encoding/Hebrew (Windows-1255)"),
698          ENC_ACTION(C_WINDOWS_1255)},
699         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
700
701         {N_("/_Options/Character _encoding/Turkish (ISO-8859-_9)"),
702          ENC_ACTION(C_ISO_8859_9)},
703         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
704
705         {N_("/_Options/Character _encoding/Cyrillic (ISO-8859-_5)"),
706          ENC_ACTION(C_ISO_8859_5)},
707         {N_("/_Options/Character _encoding/Cyrillic (KOI8-_R)"),
708          ENC_ACTION(C_KOI8_R)},
709         {N_("/_Options/Character _encoding/Cyrillic (KOI8-U)"),
710          ENC_ACTION(C_KOI8_U)},
711         {N_("/_Options/Character _encoding/Cyrillic (Windows-1251)"),
712          ENC_ACTION(C_WINDOWS_1251)},
713         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
714
715         {N_("/_Options/Character _encoding/Japanese (ISO-2022-_JP)"),
716          ENC_ACTION(C_ISO_2022_JP)},
717         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
718
719         {N_("/_Options/Character _encoding/Simplified Chinese (_GB2312)"),
720          ENC_ACTION(C_GB2312)},
721         {N_("/_Options/Character _encoding/Simplified Chinese (GBK)"),
722          ENC_ACTION(C_GBK)},
723         {N_("/_Options/Character _encoding/Traditional Chinese (_Big5)"),
724          ENC_ACTION(C_BIG5)},
725         {N_("/_Options/Character _encoding/Traditional Chinese (EUC-_TW)"),
726          ENC_ACTION(C_EUC_TW)},
727         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
728
729         {N_("/_Options/Character _encoding/Korean (EUC-_KR)"),
730          ENC_ACTION(C_EUC_KR)},
731         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
732
733         {N_("/_Options/Character _encoding/Thai (TIS-620)"),
734          ENC_ACTION(C_TIS_620)},
735         {N_("/_Options/Character _encoding/Thai (Windows-874)"),
736          ENC_ACTION(C_WINDOWS_874)},
737
738         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
739         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
740         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
741         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
742         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
743         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
744         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
745 };
746
747 static GtkTargetEntry compose_mime_types[] =
748 {
749         {"text/uri-list", 0, 0},
750         {"text/plain", 0, 0},
751         {"STRING", 0, 0}
752 };
753
754 static gboolean compose_put_existing_to_front(MsgInfo *info)
755 {
756         GList *compose_list = compose_get_compose_list();
757         GList *elem = NULL;
758         
759         if (compose_list) {
760                 for (elem = compose_list; elem != NULL && elem->data != NULL; 
761                      elem = elem->next) {
762                         Compose *c = (Compose*)elem->data;
763
764                         if (!c->targetinfo || !c->targetinfo->msgid ||
765                             !info->msgid)
766                                 continue;
767
768                         if (!strcmp(c->targetinfo->msgid, info->msgid)) {
769                                 gtkut_window_popup(c->window);
770                                 return TRUE;
771                         }
772                 }
773         }
774         return FALSE;
775 }
776
777 static GdkColor quote_color = 
778         {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
779
780 static GdkColor signature_color = {
781         (gulong)0,
782         (gushort)0x7fff,
783         (gushort)0x7fff,
784         (gushort)0x7fff
785 };
786
787 static GdkColor uri_color = {
788         (gulong)0,
789         (gushort)0,
790         (gushort)0,
791         (gushort)0
792 };
793
794 static void compose_create_tags(GtkTextView *text, Compose *compose)
795 {
796         GtkTextBuffer *buffer;
797         GdkColor black = {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
798
799         buffer = gtk_text_view_get_buffer(text);
800         
801         if (prefs_common.enable_color) {
802                 /* grab the quote colors, converting from an int to a GdkColor */
803                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
804                                                &quote_color);
805                 gtkut_convert_int_to_gdk_color(prefs_common.signature_col,
806                                                &signature_color);
807                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
808                                                &uri_color);
809         } else {
810                 signature_color = quote_color = uri_color = black;
811         }
812
813         gtk_text_buffer_create_tag(buffer, "quote",
814                                    "foreground-gdk", &quote_color,
815                                    NULL);
816         gtk_text_buffer_create_tag(buffer, "signature",
817                                    "foreground-gdk", &signature_color,
818                                    NULL);
819         gtk_text_buffer_create_tag(buffer, "link",
820                                          "foreground-gdk", &uri_color,
821                                          NULL);
822         compose->no_wrap_tag = gtk_text_buffer_create_tag(buffer, "no_wrap", NULL);
823         compose->no_join_tag = gtk_text_buffer_create_tag(buffer, "no_join", NULL);
824 }
825
826 Compose *compose_new(PrefsAccount *account, const gchar *mailto,
827                      GPtrArray *attach_files)
828 {
829         return compose_generic_new(account, mailto, NULL, attach_files, NULL);
830 }
831
832 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
833 {
834         return compose_generic_new(account, NULL, item, NULL, NULL);
835 }
836
837 Compose *compose_new_with_list( PrefsAccount *account, GList *listAddress )
838 {
839         return compose_generic_new( account, NULL, NULL, NULL, listAddress );
840 }
841
842 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item,
843                              GPtrArray *attach_files, GList *listAddress )
844 {
845         Compose *compose;
846         GtkTextView *textview;
847         GtkTextBuffer *textbuf;
848         GtkTextIter iter;
849         GtkItemFactory *ifactory;
850
851         if (item && item->prefs && item->prefs->enable_default_account)
852                 account = account_find_from_id(item->prefs->default_account);
853
854         if (!account) account = cur_account;
855         g_return_val_if_fail(account != NULL, NULL);
856
857         compose = compose_create(account, COMPOSE_NEW);
858         ifactory = gtk_item_factory_from_widget(compose->menubar);
859
860         compose->replyinfo = NULL;
861         compose->fwdinfo   = NULL;
862
863         textview = GTK_TEXT_VIEW(compose->text);
864         textbuf = gtk_text_view_get_buffer(textview);
865         compose_create_tags(textview, compose);
866
867         undo_block(compose->undostruct);
868 #ifdef USE_ASPELL
869         if (item && item->prefs && item->prefs->enable_default_dictionary &&
870             compose->gtkaspell) 
871                 gtkaspell_change_dict(compose->gtkaspell, 
872                     item->prefs->default_dictionary);
873 #endif
874
875         if (account->auto_sig)
876                 compose_insert_sig(compose, FALSE);
877         gtk_text_buffer_get_start_iter(textbuf, &iter);
878         gtk_text_buffer_place_cursor(textbuf, &iter);
879
880         if (account->protocol != A_NNTP) {
881                 if (mailto && *mailto != '\0') {
882                         compose_entries_set(compose, mailto);
883
884                 } else if (item && item->prefs->enable_default_to) {
885                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
886                         compose_entry_mark_default_to(compose, item->prefs->default_to);
887                 }
888                 if (item && item->ret_rcpt) {
889                         menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
890                 }
891         } else {
892                 if (mailto) {
893                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
894                 } else if (item) {
895                         compose_entry_append(compose, item->path, COMPOSE_NEWSGROUPS);
896                 }
897                 /*
898                  * CLAWS: just don't allow return receipt request, even if the user
899                  * may want to send an email. simple but foolproof.
900                  */
901                 menu_set_sensitive(ifactory, "/Options/Request Return Receipt", FALSE); 
902         }
903         compose_add_field_list( compose, listAddress );
904
905         if (attach_files) {
906                 gint i;
907                 gchar *file;
908
909                 for (i = 0; i < attach_files->len; i++) {
910                         file = g_ptr_array_index(attach_files, i);
911                         compose_attach_append(compose, file, file, NULL);
912                 }
913         }
914
915         compose_show_first_last_header(compose, TRUE);
916
917         /* Set save folder */
918         if (item && item->prefs && item->prefs->save_copy_to_folder) {
919                 gchar *folderidentifier;
920
921                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
922                 folderidentifier = folder_item_get_identifier(item);
923                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
924                 g_free(folderidentifier);
925         }
926         
927         gtk_widget_grab_focus(compose->header_last->entry);
928
929         undo_unblock(compose->undostruct);
930
931         if (prefs_common.auto_exteditor)
932                 compose_exec_ext_editor(compose);
933
934         compose->modified = FALSE;
935         compose_set_title(compose);
936         return compose;
937 }
938
939 static void compose_force_encryption(Compose *compose, PrefsAccount *account,
940                 gboolean override_pref)
941 {
942         gchar *privacy = NULL;
943
944         g_return_if_fail(compose != NULL);
945         g_return_if_fail(account != NULL);
946
947         if (override_pref == FALSE && account->default_encrypt_reply == FALSE)
948                 return;
949
950         if (account->default_privacy_system
951         &&  strlen(account->default_privacy_system)) {
952                 privacy = account->default_privacy_system;
953         } else {
954                 GSList *privacy_avail = privacy_get_system_ids();
955                 if (privacy_avail && g_slist_length(privacy_avail)) {
956                         privacy = (gchar *)(privacy_avail->data);
957                 }
958         }
959         if (privacy != NULL) {
960                 compose->privacy_system = g_strdup(privacy);
961                 compose_update_privacy_system_menu_item(compose, FALSE);
962                 compose_use_encryption(compose, TRUE);
963         }
964 }       
965
966 static void compose_force_signing(Compose *compose, PrefsAccount *account)
967 {
968         gchar *privacy = NULL;
969
970         if (account->default_privacy_system
971         &&  strlen(account->default_privacy_system)) {
972                 privacy = account->default_privacy_system;
973         } else {
974                 GSList *privacy_avail = privacy_get_system_ids();
975                 if (privacy_avail && g_slist_length(privacy_avail)) {
976                         privacy = (gchar *)(privacy_avail->data);
977                 }
978         }
979         if (privacy != NULL) {
980                 compose->privacy_system = g_strdup(privacy);
981                 compose_update_privacy_system_menu_item(compose, FALSE);
982                 compose_use_signing(compose, TRUE);
983         }
984 }       
985
986 Compose *compose_reply_mode(ComposeMode mode, GSList *msginfo_list, gchar *body)
987 {
988         MsgInfo *msginfo;
989         guint list_len;
990         Compose *compose = NULL;
991         g_return_val_if_fail(msginfo_list != NULL, NULL);
992
993         msginfo = (MsgInfo*)g_slist_nth_data(msginfo_list, 0);
994         g_return_val_if_fail(msginfo != NULL, NULL);
995
996         list_len = g_slist_length(msginfo_list);
997
998         switch (mode) {
999         case COMPOSE_REPLY:
1000                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1001                               FALSE, prefs_common.default_reply_list, FALSE, body);
1002                 break;
1003         case COMPOSE_REPLY_WITH_QUOTE:
1004                 compose = compose_reply(msginfo, TRUE, 
1005                         FALSE, prefs_common.default_reply_list, FALSE, body);
1006                 break;
1007         case COMPOSE_REPLY_WITHOUT_QUOTE:
1008                 compose = compose_reply(msginfo, FALSE, 
1009                         FALSE, prefs_common.default_reply_list, FALSE, NULL);
1010                 break;
1011         case COMPOSE_REPLY_TO_SENDER:
1012                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1013                               FALSE, FALSE, TRUE, body);
1014                 break;
1015         case COMPOSE_FOLLOWUP_AND_REPLY_TO:
1016                 compose = compose_followup_and_reply_to(msginfo,
1017                                               prefs_common.reply_with_quote,
1018                                               FALSE, FALSE, body);
1019                 break;
1020         case COMPOSE_REPLY_TO_SENDER_WITH_QUOTE:
1021                 compose = compose_reply(msginfo, TRUE, 
1022                         FALSE, FALSE, TRUE, body);
1023                 break;
1024         case COMPOSE_REPLY_TO_SENDER_WITHOUT_QUOTE:
1025                 compose = compose_reply(msginfo, FALSE, 
1026                         FALSE, FALSE, TRUE, NULL);
1027                 break;
1028         case COMPOSE_REPLY_TO_ALL:
1029                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1030                         TRUE, FALSE, FALSE, body);
1031                 break;
1032         case COMPOSE_REPLY_TO_ALL_WITH_QUOTE:
1033                 compose = compose_reply(msginfo, TRUE, 
1034                         TRUE, FALSE, FALSE, body);
1035                 break;
1036         case COMPOSE_REPLY_TO_ALL_WITHOUT_QUOTE:
1037                 compose = compose_reply(msginfo, FALSE, 
1038                         TRUE, FALSE, FALSE, NULL);
1039                 break;
1040         case COMPOSE_REPLY_TO_LIST:
1041                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1042                         FALSE, TRUE, FALSE, body);
1043                 break;
1044         case COMPOSE_REPLY_TO_LIST_WITH_QUOTE:
1045                 compose = compose_reply(msginfo, TRUE, 
1046                         FALSE, TRUE, FALSE, body);
1047                 break;
1048         case COMPOSE_REPLY_TO_LIST_WITHOUT_QUOTE:
1049                 compose = compose_reply(msginfo, FALSE, 
1050                         FALSE, TRUE, FALSE, NULL);
1051                 break;
1052         case COMPOSE_FORWARD:
1053                 if (prefs_common.forward_as_attachment) {
1054                         compose = compose_reply_mode(COMPOSE_FORWARD_AS_ATTACH, msginfo_list, body);
1055                         return compose;
1056                 } else {
1057                         compose = compose_reply_mode(COMPOSE_FORWARD_INLINE, msginfo_list, body);
1058                         return compose;
1059                 }
1060                 break;
1061         case COMPOSE_FORWARD_INLINE:
1062                 /* check if we reply to more than one Message */
1063                 if (list_len == 1) {
1064                         compose = compose_forward(NULL, msginfo, FALSE, body, FALSE);
1065                         break;
1066                 } 
1067                 /* more messages FALL THROUGH */
1068         case COMPOSE_FORWARD_AS_ATTACH:
1069                 compose = compose_forward_multiple(NULL, msginfo_list);
1070                 break;
1071         case COMPOSE_REDIRECT:
1072                 compose = compose_redirect(NULL, msginfo);
1073                 break;
1074         default:
1075                 g_warning("compose_reply(): invalid Compose Mode: %d\n", mode);
1076         }
1077         return compose;
1078 }
1079
1080 Compose *compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
1081                    gboolean to_ml, gboolean to_sender, 
1082                    const gchar *body)
1083 {
1084         return compose_generic_reply(msginfo, quote, to_all, to_ml, 
1085                               to_sender, FALSE, body);
1086 }
1087
1088 Compose *compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
1089                                    gboolean to_all,
1090                                    gboolean to_sender,
1091                                    const gchar *body)
1092 {
1093         return compose_generic_reply(msginfo, quote, to_all, FALSE, 
1094                               to_sender, TRUE, body);
1095 }
1096
1097 static void compose_extract_original_charset(Compose *compose)
1098 {
1099         MsgInfo *info = NULL;
1100         if (compose->replyinfo) {
1101                 info = compose->replyinfo;
1102         } else if (compose->fwdinfo) {
1103                 info = compose->fwdinfo;
1104         } else if (compose->targetinfo) {
1105                 info = compose->targetinfo;
1106         }
1107         if (info) {
1108                 MimeInfo *mimeinfo = procmime_scan_message(info);
1109                 MimeInfo *partinfo = mimeinfo;
1110                 while (partinfo && partinfo->type != MIMETYPE_TEXT)
1111                         partinfo = procmime_mimeinfo_next(partinfo);
1112                 if (partinfo) {
1113                         compose->orig_charset = 
1114                                 g_strdup(procmime_mimeinfo_get_parameter(
1115                                                 partinfo, "charset"));
1116                 }
1117                 procmime_mimeinfo_free_all(mimeinfo);
1118         }
1119 }
1120
1121 #define SIGNAL_BLOCK(buffer) {                                  \
1122         g_signal_handlers_block_by_func(G_OBJECT(buffer),       \
1123                                 G_CALLBACK(compose_changed_cb), \
1124                                 compose);                       \
1125         g_signal_handlers_block_by_func(G_OBJECT(buffer),       \
1126                                 G_CALLBACK(text_inserted),      \
1127                                 compose);                       \
1128 }
1129
1130 #define SIGNAL_UNBLOCK(buffer) {                                \
1131         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),     \
1132                                 G_CALLBACK(compose_changed_cb), \
1133                                 compose);                       \
1134         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),     \
1135                                 G_CALLBACK(text_inserted),      \
1136                                 compose);                       \
1137 }
1138
1139 static Compose *compose_generic_reply(MsgInfo *msginfo, gboolean quote,
1140                                   gboolean to_all, gboolean to_ml,
1141                                   gboolean to_sender,
1142                                   gboolean followup_and_reply_to,
1143                                   const gchar *body)
1144 {
1145         GtkItemFactory *ifactory;
1146         Compose *compose;
1147         PrefsAccount *account = NULL;
1148         PrefsAccount *reply_account;
1149         GtkTextView *textview;
1150         GtkTextBuffer *textbuf;
1151
1152         g_return_val_if_fail(msginfo != NULL, NULL);
1153         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1154
1155         account = account_get_reply_account(msginfo, prefs_common.reply_account_autosel);
1156         
1157         g_return_val_if_fail(account != NULL, NULL);
1158
1159         if (to_sender && account->protocol == A_NNTP &&
1160             !followup_and_reply_to) {
1161                 reply_account =
1162                         account_find_from_address(account->address);
1163                 if (!reply_account)
1164                         reply_account = compose_current_mail_account();
1165                 if (!reply_account)
1166                         return NULL;
1167         } else
1168                 reply_account = account;
1169
1170         compose = compose_create(account, COMPOSE_REPLY);
1171         ifactory = gtk_item_factory_from_widget(compose->menubar);
1172
1173         menu_set_active(ifactory, "/Options/Remove references", FALSE);
1174         menu_set_sensitive(ifactory, "/Options/Remove references", TRUE);
1175
1176         compose->replyinfo = procmsg_msginfo_get_full_info(msginfo);
1177
1178         if (!compose->replyinfo)
1179                 compose->replyinfo = procmsg_msginfo_copy(msginfo);
1180         
1181         compose_extract_original_charset(compose);
1182         
1183         if (msginfo->folder && msginfo->folder->ret_rcpt)
1184                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1185
1186         /* Set save folder */
1187         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1188                 gchar *folderidentifier;
1189
1190                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1191                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1192                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1193                 g_free(folderidentifier);
1194         }
1195
1196         if (compose_parse_header(compose, msginfo) < 0) return NULL;
1197         compose_reply_set_entry(compose, msginfo, to_all, to_ml, 
1198                                 to_sender, followup_and_reply_to);
1199         compose_show_first_last_header(compose, TRUE);
1200
1201         textview = (GTK_TEXT_VIEW(compose->text));
1202         textbuf = gtk_text_view_get_buffer(textview);
1203         compose_create_tags(textview, compose);
1204
1205         undo_block(compose->undostruct);
1206 #ifdef USE_ASPELL
1207         if (msginfo->folder && msginfo->folder->prefs && 
1208             msginfo->folder->prefs && 
1209             msginfo->folder->prefs->enable_default_dictionary &&
1210             compose->gtkaspell)
1211                 gtkaspell_change_dict(compose->gtkaspell, 
1212                     msginfo->folder->prefs->default_dictionary);
1213 #endif
1214
1215         if (quote) {
1216                 gchar *qmark;
1217
1218                 if (prefs_common.quotemark && *prefs_common.quotemark)
1219                         qmark = prefs_common.quotemark;
1220                 else
1221                         qmark = "> ";
1222
1223                 compose_quote_fmt(compose, compose->replyinfo,
1224                                   prefs_common.quotefmt,
1225                                   qmark, body, FALSE);
1226         }
1227         if (procmime_msginfo_is_encrypted(compose->replyinfo)) {
1228                 compose_force_encryption(compose, account, FALSE);
1229         }
1230
1231         SIGNAL_BLOCK(textbuf);
1232         
1233         if (account->auto_sig)
1234                 compose_insert_sig(compose, FALSE);
1235
1236         compose_wrap_all(compose);
1237
1238         SIGNAL_UNBLOCK(textbuf);
1239         
1240         gtk_widget_grab_focus(compose->text);
1241
1242         undo_unblock(compose->undostruct);
1243
1244         if (prefs_common.auto_exteditor)
1245                 compose_exec_ext_editor(compose);
1246                 
1247         compose->modified = FALSE;
1248         compose_set_title(compose);
1249         return compose;
1250 }
1251
1252 #define INSERT_FW_HEADER(var, hdr) \
1253 if (msginfo->var && *msginfo->var) { \
1254         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1255         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1256         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1257 }
1258
1259 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1260                          gboolean as_attach, const gchar *body,
1261                          gboolean no_extedit)
1262 {
1263         Compose *compose;
1264         GtkTextView *textview;
1265         GtkTextBuffer *textbuf;
1266         GtkTextIter iter;
1267
1268         g_return_val_if_fail(msginfo != NULL, NULL);
1269         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1270
1271         if (!account && 
1272             !(account = compose_guess_forward_account_from_msginfo
1273                                 (msginfo)))
1274                 account = cur_account;
1275
1276         compose = compose_create(account, COMPOSE_FORWARD);
1277
1278         compose->fwdinfo = procmsg_msginfo_get_full_info(msginfo);
1279         if (!compose->fwdinfo)
1280                 compose->fwdinfo = procmsg_msginfo_copy(msginfo);
1281
1282         compose_extract_original_charset(compose);
1283
1284         if (msginfo->subject && *msginfo->subject) {
1285                 gchar *buf, *buf2, *p;
1286
1287                 buf = p = g_strdup(msginfo->subject);
1288                 p += subject_get_prefix_length(p);
1289                 memmove(buf, p, strlen(p) + 1);
1290
1291                 buf2 = g_strdup_printf("Fw: %s", buf);
1292                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1293                 
1294                 g_free(buf);
1295                 g_free(buf2);
1296         }
1297
1298         textview = GTK_TEXT_VIEW(compose->text);
1299         textbuf = gtk_text_view_get_buffer(textview);
1300         compose_create_tags(textview, compose);
1301         
1302         undo_block(compose->undostruct);
1303         if (as_attach) {
1304                 gchar *msgfile;
1305
1306                 msgfile = procmsg_get_message_file_path(msginfo);
1307                 if (!is_file_exist(msgfile))
1308                         g_warning("%s: file not exist\n", msgfile);
1309                 else
1310                         compose_attach_append(compose, msgfile, msgfile,
1311                                               "message/rfc822");
1312
1313                 g_free(msgfile);
1314         } else {
1315                 gchar *qmark;
1316                 MsgInfo *full_msginfo;
1317
1318                 full_msginfo = procmsg_msginfo_get_full_info(msginfo);
1319                 if (!full_msginfo)
1320                         full_msginfo = procmsg_msginfo_copy(msginfo);
1321
1322                 if (prefs_common.fw_quotemark &&
1323                     *prefs_common.fw_quotemark)
1324                         qmark = prefs_common.fw_quotemark;
1325                 else
1326                         qmark = "> ";
1327
1328                 compose_quote_fmt(compose, full_msginfo,
1329                                   prefs_common.fw_quotefmt,
1330                                   qmark, body, FALSE);
1331                 compose_attach_parts(compose, msginfo);
1332
1333                 procmsg_msginfo_free(full_msginfo);
1334         }
1335
1336         SIGNAL_BLOCK(textbuf);
1337
1338         if (account->auto_sig)
1339                 compose_insert_sig(compose, FALSE);
1340
1341         compose_wrap_all(compose);
1342
1343         SIGNAL_UNBLOCK(textbuf);
1344         
1345         gtk_text_buffer_get_start_iter(textbuf, &iter);
1346         gtk_text_buffer_place_cursor(textbuf, &iter);
1347
1348         gtk_widget_grab_focus(compose->header_last->entry);
1349
1350         if (!no_extedit && prefs_common.auto_exteditor)
1351                 compose_exec_ext_editor(compose);
1352         
1353         /*save folder*/
1354         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1355                 gchar *folderidentifier;
1356
1357                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1358                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1359                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1360                 g_free(folderidentifier);
1361         }
1362
1363         undo_unblock(compose->undostruct);
1364         
1365         compose->modified = FALSE;
1366         compose_set_title(compose);
1367         return compose;
1368 }
1369
1370 #undef INSERT_FW_HEADER
1371
1372 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1373 {
1374         Compose *compose;
1375         GtkTextView *textview;
1376         GtkTextBuffer *textbuf;
1377         GtkTextIter iter;
1378         GSList *msginfo;
1379         gchar *msgfile;
1380         gboolean single_mail = TRUE;
1381         
1382         g_return_val_if_fail(msginfo_list != NULL, NULL);
1383
1384         if (g_slist_length(msginfo_list) > 1)
1385                 single_mail = FALSE;
1386
1387         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next)
1388                 if (((MsgInfo *)msginfo->data)->folder == NULL)
1389                         return NULL;
1390
1391         /* guess account from first selected message */
1392         if (!account && 
1393             !(account = compose_guess_forward_account_from_msginfo
1394                                 (msginfo_list->data)))
1395                 account = cur_account;
1396
1397         g_return_val_if_fail(account != NULL, NULL);
1398
1399         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1400                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1401                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1402         }
1403
1404         compose = compose_create(account, COMPOSE_FORWARD);
1405
1406         textview = GTK_TEXT_VIEW(compose->text);
1407         textbuf = gtk_text_view_get_buffer(textview);
1408         compose_create_tags(textview, compose);
1409         
1410         undo_block(compose->undostruct);
1411         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1412                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1413                 if (!is_file_exist(msgfile))
1414                         g_warning("%s: file not exist\n", msgfile);
1415                 else
1416                         compose_attach_append(compose, msgfile, msgfile,
1417                                 "message/rfc822");
1418                 g_free(msgfile);
1419         }
1420         
1421         if (single_mail) {
1422                 MsgInfo *info = (MsgInfo *)msginfo_list->data;
1423                 if (info->subject && *info->subject) {
1424                         gchar *buf, *buf2, *p;
1425
1426                         buf = p = g_strdup(info->subject);
1427                         p += subject_get_prefix_length(p);
1428                         memmove(buf, p, strlen(p) + 1);
1429
1430                         buf2 = g_strdup_printf("Fw: %s", buf);
1431                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1432
1433                         g_free(buf);
1434                         g_free(buf2);
1435                 }
1436         } else {
1437                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1438                         _("Fw: multiple emails"));
1439         }
1440
1441         SIGNAL_BLOCK(textbuf);
1442         
1443         if (account->auto_sig)
1444                 compose_insert_sig(compose, FALSE);
1445
1446         compose_wrap_all(compose);
1447
1448         SIGNAL_UNBLOCK(textbuf);
1449         
1450         gtk_text_buffer_get_start_iter(textbuf, &iter);
1451         gtk_text_buffer_place_cursor(textbuf, &iter);
1452
1453         gtk_widget_grab_focus(compose->header_last->entry);
1454         undo_unblock(compose->undostruct);
1455         compose->modified = FALSE;
1456         compose_set_title(compose);
1457         return compose;
1458 }
1459
1460 static gboolean compose_is_sig_separator(Compose *compose, GtkTextBuffer *textbuf, GtkTextIter *iter) 
1461 {
1462         GtkTextIter start = *iter;
1463         GtkTextIter end_iter;
1464         int start_pos = gtk_text_iter_get_offset(&start);
1465         gchar *str = NULL;
1466         if (!compose->account->sig_sep)
1467                 return FALSE;
1468         
1469         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1470                 start_pos+strlen(compose->account->sig_sep));
1471
1472         /* check sig separator */
1473         str = gtk_text_iter_get_text(&start, &end_iter);
1474         if (!strcmp(str, compose->account->sig_sep)) {
1475                 gchar *tmp = NULL;
1476                 /* check end of line (\n) */
1477                 gtk_text_buffer_get_iter_at_offset(textbuf, &start,
1478                         start_pos+strlen(compose->account->sig_sep));
1479                 gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1480                         start_pos+strlen(compose->account->sig_sep)+1);
1481                 tmp = gtk_text_iter_get_text(&start, &end_iter);
1482                 if (!strcmp(tmp,"\n")) {
1483                         g_free(str);
1484                         g_free(tmp);
1485                         return TRUE;
1486                 }
1487                 g_free(tmp);    
1488         }
1489         g_free(str);
1490
1491         return FALSE;
1492 }
1493
1494 static void compose_colorize_signature(Compose *compose)
1495 {
1496         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
1497         GtkTextIter iter;
1498         GtkTextIter end_iter;
1499         gtk_text_buffer_get_start_iter(buffer, &iter);
1500         while (gtk_text_iter_forward_line(&iter))
1501                 if (compose_is_sig_separator(compose, buffer, &iter)) {
1502                         gtk_text_buffer_get_end_iter(buffer, &end_iter);
1503                         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &end_iter);
1504                 }
1505 }
1506
1507 void compose_reedit(MsgInfo *msginfo)
1508 {
1509         Compose *compose = NULL;
1510         PrefsAccount *account = NULL;
1511         GtkTextView *textview;
1512         GtkTextBuffer *textbuf;
1513         GtkTextMark *mark;
1514         GtkTextIter iter;
1515         FILE *fp;
1516         gchar buf[BUFFSIZE];
1517         gboolean use_signing = FALSE;
1518         gboolean use_encryption = FALSE;
1519         gchar *privacy_system = NULL;
1520
1521         g_return_if_fail(msginfo != NULL);
1522         g_return_if_fail(msginfo->folder != NULL);
1523
1524         if (compose_put_existing_to_front(msginfo)) 
1525                 return;
1526
1527         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1528             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1529                 gchar queueheader_buf[BUFFSIZE];
1530                 gint id, param;
1531
1532                 /* Select Account from queue headers */
1533                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1534                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1535                         id = atoi(&queueheader_buf[strlen("X-Sylpheed-Account-Id:")]);
1536                         account = account_find_from_id(id);
1537                 }
1538                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1539                                              sizeof(queueheader_buf), "NAID:")) {
1540                         id = atoi(&queueheader_buf[strlen("NAID:")]);
1541                         account = account_find_from_id(id);
1542                 }
1543                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1544                                                     sizeof(queueheader_buf), "MAID:")) {
1545                         id = atoi(&queueheader_buf[strlen("MAID:")]);
1546                         account = account_find_from_id(id);
1547                 }
1548                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1549                                                                 sizeof(queueheader_buf), "S:")) {
1550                         account = account_find_from_address(queueheader_buf);
1551                 }
1552                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1553                                              sizeof(queueheader_buf), "X-Sylpheed-Sign:")) {
1554                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Sign:")]);
1555                         use_signing = param;
1556                         
1557                 }
1558                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1559                                              sizeof(queueheader_buf), "X-Sylpheed-Encrypt:")) {
1560                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Encrypt:")]);
1561                         use_encryption = param;
1562                 }
1563                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1564                                             sizeof(queueheader_buf), "X-Sylpheed-Privacy-System:")) {
1565                         privacy_system = g_strdup(&queueheader_buf[strlen("X-Sylpheed-Privacy-System:")]);
1566                 }
1567                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1568                                              sizeof(queueheader_buf), "X-Priority: ")) {
1569                         param = atoi(&queueheader_buf[strlen("X-Priority: ")]); /* mind the space */
1570                         compose->priority = param;
1571                 }
1572         } else 
1573                 account = msginfo->folder->folder->account;
1574
1575         if (!account && prefs_common.reedit_account_autosel) {
1576                 gchar from[BUFFSIZE];
1577                 if (!procheader_get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1578                         extract_address(from);
1579                         account = account_find_from_address(from);
1580                 }
1581         }
1582         if (!account) account = cur_account;
1583         g_return_if_fail(account != NULL);
1584
1585         compose = compose_create(account, COMPOSE_REEDIT);
1586         if (privacy_system != NULL) {
1587                 compose->privacy_system = privacy_system;
1588                 compose_use_signing(compose, use_signing);
1589                 compose_use_encryption(compose, use_encryption);
1590                 compose_update_privacy_system_menu_item(compose, FALSE);
1591         } else {
1592                 activate_privacy_system(compose, account, FALSE);
1593         }
1594         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1595
1596         compose_extract_original_charset(compose);
1597
1598         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1599             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1600                 gchar queueheader_buf[BUFFSIZE];
1601
1602                 /* Set message save folder */
1603                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1604                         gint startpos = 0;
1605
1606                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1607                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1608                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1609                 }
1610                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "RRCPT:")) {
1611                         gint active = atoi(&queueheader_buf[strlen("RRCPT:")]);
1612                         if (active) {
1613                                 GtkItemFactory *ifactory;
1614                                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1615                                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1616                         }
1617                 }
1618         }
1619         
1620         if (compose_parse_header(compose, msginfo) < 0) return;
1621         compose_reedit_set_entry(compose, msginfo);
1622
1623         textview = GTK_TEXT_VIEW(compose->text);
1624         textbuf = gtk_text_view_get_buffer(textview);
1625         compose_create_tags(textview, compose);
1626
1627         mark = gtk_text_buffer_get_insert(textbuf);
1628         gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1629
1630         g_signal_handlers_block_by_func(G_OBJECT(textbuf),
1631                                         G_CALLBACK(compose_changed_cb),
1632                                         compose);
1633         
1634         if (procmime_msginfo_is_encrypted(msginfo)) {
1635                 fp = procmime_get_first_encrypted_text_content(msginfo);
1636                 if (fp) 
1637                         compose_force_encryption(compose, account, TRUE);
1638         } else
1639                 fp = procmime_get_first_text_content(msginfo);
1640         if (fp == NULL)
1641                 g_warning("Can't get text part\n");
1642
1643         if (fp != NULL) {
1644                 gboolean prev_autowrap = compose->autowrap;
1645
1646                 compose->autowrap = FALSE;
1647                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1648                         strcrchomp(buf);
1649                         gtk_text_buffer_insert(textbuf, &iter, buf, -1);
1650                 }
1651                 compose_wrap_all_full(compose, FALSE);
1652                 compose->autowrap = prev_autowrap;
1653                 fclose(fp);
1654         }
1655         
1656         compose_attach_parts(compose, msginfo);
1657
1658         compose_colorize_signature(compose);
1659
1660         g_signal_handlers_unblock_by_func(G_OBJECT(textbuf),
1661                                         G_CALLBACK(compose_changed_cb),
1662                                         compose);
1663
1664         gtk_widget_grab_focus(compose->text);
1665
1666         if (prefs_common.auto_exteditor)
1667                 compose_exec_ext_editor(compose);
1668         compose->modified = FALSE;
1669         compose_set_title(compose);
1670 }
1671
1672 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
1673 {
1674         Compose *compose;
1675         gchar *filename;
1676         GtkItemFactory *ifactory;
1677         FolderItem *item;
1678
1679         g_return_val_if_fail(msginfo != NULL, NULL);
1680
1681         if (!account)
1682                 account = account_get_reply_account(msginfo,
1683                                         prefs_common.reply_account_autosel);
1684         g_return_val_if_fail(account != NULL, NULL);
1685
1686         compose = compose_create(account, COMPOSE_REDIRECT);
1687         ifactory = gtk_item_factory_from_widget(compose->menubar);
1688         compose_create_tags(GTK_TEXT_VIEW(compose->text), compose);
1689         compose->replyinfo = NULL;
1690         compose->fwdinfo = NULL;
1691
1692         compose_show_first_last_header(compose, TRUE);
1693
1694         gtk_widget_grab_focus(compose->header_last->entry);
1695
1696         filename = procmsg_get_message_file_path(msginfo);
1697         if (filename == NULL)
1698                 return NULL;
1699
1700         compose->redirect_filename = filename;
1701         
1702         /* Set save folder */
1703         item = msginfo->folder;
1704         if (item && item->prefs && item->prefs->save_copy_to_folder) {
1705                 gchar *folderidentifier;
1706
1707                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
1708                 folderidentifier = folder_item_get_identifier(item);
1709                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1710                 g_free(folderidentifier);
1711         }
1712
1713         compose_attach_parts(compose, msginfo);
1714
1715         if (msginfo->subject)
1716                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1717                                    msginfo->subject);
1718         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1719
1720         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL, FALSE);
1721         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), FALSE);
1722
1723         compose_colorize_signature(compose);
1724
1725         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1726         menu_set_sensitive(ifactory, "/Add...", FALSE);
1727         menu_set_sensitive(ifactory, "/Remove", FALSE);
1728         menu_set_sensitive(ifactory, "/Properties...", FALSE);
1729
1730         ifactory = gtk_item_factory_from_widget(compose->menubar);
1731         menu_set_sensitive(ifactory, "/Message/Save", FALSE);
1732         menu_set_sensitive(ifactory, "/Message/Insert file", FALSE);
1733         menu_set_sensitive(ifactory, "/Message/Attach file", FALSE);
1734         menu_set_sensitive(ifactory, "/Message/Insert signature", FALSE);
1735         menu_set_sensitive(ifactory, "/Edit", FALSE);
1736         menu_set_sensitive(ifactory, "/Options", FALSE);
1737         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1738         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1739         
1740         gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1741         gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1742         gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1743         gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1744         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1745         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, FALSE);
1746         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, FALSE);
1747
1748         compose->modified = FALSE;
1749         compose_set_title(compose);
1750         return compose;
1751 }
1752
1753 GList *compose_get_compose_list(void)
1754 {
1755         return compose_list;
1756 }
1757
1758 void compose_entry_append(Compose *compose, const gchar *address,
1759                           ComposeEntryType type)
1760 {
1761         gchar *header;
1762         gchar *cur, *begin;
1763         gboolean in_quote = FALSE;
1764         if (!address || *address == '\0') return;
1765
1766         switch (type) {
1767         case COMPOSE_CC:
1768                 header = N_("Cc:");
1769                 break;
1770         case COMPOSE_BCC:
1771                 header = N_("Bcc:");
1772                 break;
1773         case COMPOSE_REPLYTO:
1774                 header = N_("Reply-To:");
1775                 break;
1776         case COMPOSE_NEWSGROUPS:
1777                 header = N_("Newsgroups:");
1778                 break;
1779         case COMPOSE_FOLLOWUPTO:
1780                 header = N_( "Followup-To:");
1781                 break;
1782         case COMPOSE_TO:
1783         default:
1784                 header = N_("To:");
1785                 break;
1786         }
1787         header = prefs_common.trans_hdr ? gettext(header) : header;
1788         
1789         cur = begin = (gchar *)address;
1790         
1791         /* we separate the line by commas, but not if we're inside a quoted
1792          * string */
1793         while (*cur != '\0') {
1794                 if (*cur == '"') 
1795                         in_quote = !in_quote;
1796                 if (*cur == ',' && !in_quote) {
1797                         gchar *tmp = g_strdup(begin);
1798                         gchar *o_tmp = tmp;
1799                         tmp[cur-begin]='\0';
1800                         cur++;
1801                         begin = cur;
1802                         while (*tmp == ' ')
1803                                 tmp++;
1804                         compose_add_header_entry(compose, header, tmp);
1805                         g_free(o_tmp);
1806                         continue;
1807                 }
1808                 cur++;
1809         }
1810         if (begin < cur) {
1811                 gchar *tmp = g_strdup(begin);
1812                 gchar *o_tmp = tmp;
1813                 tmp[cur-begin]='\0';
1814                 cur++;
1815                 begin = cur;
1816                 while (*tmp == ' ')
1817                         tmp++;
1818                 compose_add_header_entry(compose, header, tmp);
1819                 g_free(o_tmp);          
1820         }
1821 }
1822
1823 void compose_entry_mark_default_to(Compose *compose, const gchar *mailto)
1824 {
1825         static GdkColor yellow;
1826         static gboolean yellow_initialised = FALSE;
1827         GSList *h_list;
1828         GtkEntry *entry;
1829                 
1830         if (!yellow_initialised) {
1831                 gdk_color_parse("#f5f6be", &yellow);
1832                 yellow_initialised = gdk_colormap_alloc_color(
1833                         gdk_colormap_get_system(), &yellow, FALSE, TRUE);
1834                 
1835         }
1836
1837         for (h_list = compose->header_list; h_list != NULL; h_list = h_list->next) {
1838                 entry = GTK_ENTRY(((ComposeHeaderEntry *)h_list->data)->entry);
1839                 if (gtk_entry_get_text(entry) && 
1840                     !g_utf8_collate(gtk_entry_get_text(entry), mailto)) {
1841                         if (yellow_initialised)
1842                                 gtk_widget_modify_base(
1843                                         GTK_WIDGET(((ComposeHeaderEntry *)h_list->data)->entry),
1844                                         GTK_STATE_NORMAL, &yellow);
1845                 }
1846         }
1847 }
1848
1849 void compose_toolbar_cb(gint action, gpointer data)
1850 {
1851         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1852         Compose *compose = (Compose*)toolbar_item->parent;
1853         
1854         g_return_if_fail(compose != NULL);
1855
1856         switch(action) {
1857         case A_SEND:
1858                 compose_send_cb(compose, 0, NULL);
1859                 break;
1860         case A_SENDL:
1861                 compose_send_later_cb(compose, 0, NULL);
1862                 break;
1863         case A_DRAFT:
1864                 compose_draft_cb(compose, COMPOSE_QUIT_EDITING, NULL);
1865                 break;
1866         case A_INSERT:
1867                 compose_insert_file_cb(compose, 0, NULL);
1868                 break;
1869         case A_ATTACH:
1870                 compose_attach_cb(compose, 0, NULL);
1871                 break;
1872         case A_SIG:
1873                 compose_insert_sig(compose, FALSE);
1874                 break;
1875         case A_EXTEDITOR:
1876                 compose_ext_editor_cb(compose, 0, NULL);
1877                 break;
1878         case A_LINEWRAP_CURRENT:
1879                 compose_beautify_paragraph(compose, NULL, TRUE);
1880                 break;
1881         case A_LINEWRAP_ALL:
1882                 compose_wrap_all_full(compose, TRUE);
1883                 break;
1884         case A_ADDRBOOK:
1885                 compose_address_cb(compose, 0, NULL);
1886                 break;
1887 #ifdef USE_ASPELL
1888         case A_CHECK_SPELLING:
1889                 compose_check_all(compose);
1890                 break;
1891 #endif
1892         default:
1893                 break;
1894         }
1895 }
1896
1897 static void compose_entries_set(Compose *compose, const gchar *mailto)
1898 {
1899         gchar *to = NULL;
1900         gchar *cc = NULL;
1901         gchar *subject = NULL;
1902         gchar *body = NULL;
1903         gchar *temp = NULL;
1904         gint  len = 0;
1905
1906         scan_mailto_url(mailto, &to, &cc, NULL, &subject, &body);
1907
1908         if (to)
1909                 compose_entry_append(compose, to, COMPOSE_TO);
1910         if (cc)
1911                 compose_entry_append(compose, cc, COMPOSE_CC);
1912         if (subject) {
1913                 if (!g_utf8_validate (subject, -1, NULL)) {
1914                         temp = g_locale_to_utf8 (subject, -1, NULL, &len, NULL);
1915                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), temp);
1916                         g_free(temp);
1917                 } else {
1918                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1919                 }
1920         }
1921         if (body) {
1922                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1923                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1924                 GtkTextMark *mark;
1925                 GtkTextIter iter;
1926                 gboolean prev_autowrap = compose->autowrap;
1927
1928                 compose->autowrap = FALSE;
1929
1930                 mark = gtk_text_buffer_get_insert(buffer);
1931                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1932
1933                 if (!g_utf8_validate (body, -1, NULL)) {
1934                         temp = g_locale_to_utf8 (body, -1, NULL, &len, NULL);
1935                         gtk_text_buffer_insert(buffer, &iter, temp, -1);
1936                         g_free(temp);
1937                 } else {
1938                         gtk_text_buffer_insert(buffer, &iter, body, -1);
1939                 }
1940                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
1941
1942                 compose->autowrap = prev_autowrap;
1943                 if (compose->autowrap)
1944                         compose_wrap_all(compose);
1945         }
1946
1947         g_free(to);
1948         g_free(cc);
1949         g_free(subject);
1950         g_free(body);
1951 }
1952
1953 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1954 {
1955         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1956                                        {"Cc:",          NULL, TRUE},
1957                                        {"References:",  NULL, FALSE},
1958                                        {"Bcc:",         NULL, TRUE},
1959                                        {"Newsgroups:",  NULL, TRUE},
1960                                        {"Followup-To:", NULL, TRUE},
1961                                        {"List-Post:",   NULL, FALSE},
1962                                        {"X-Priority:",  NULL, FALSE},
1963                                        {NULL,           NULL, FALSE}};
1964
1965         enum
1966         {
1967                 H_REPLY_TO      = 0,
1968                 H_CC            = 1,
1969                 H_REFERENCES    = 2,
1970                 H_BCC           = 3,
1971                 H_NEWSGROUPS    = 4,
1972                 H_FOLLOWUP_TO   = 5,
1973                 H_LIST_POST     = 6,
1974                 H_X_PRIORITY    = 7
1975         };
1976
1977         FILE *fp;
1978
1979         g_return_val_if_fail(msginfo != NULL, -1);
1980
1981         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1982         procheader_get_header_fields(fp, hentry);
1983         fclose(fp);
1984
1985         if (hentry[H_REPLY_TO].body != NULL) {
1986                 if (hentry[H_REPLY_TO].body[0] != '\0') {
1987                         compose->replyto =
1988                                 conv_unmime_header(hentry[H_REPLY_TO].body,
1989                                                    NULL);
1990                 }
1991                 g_free(hentry[H_REPLY_TO].body);
1992                 hentry[H_REPLY_TO].body = NULL;
1993         }
1994         if (hentry[H_CC].body != NULL) {
1995                 compose->cc = conv_unmime_header(hentry[H_CC].body, NULL);
1996                 g_free(hentry[H_CC].body);
1997                 hentry[H_CC].body = NULL;
1998         }
1999         if (hentry[H_REFERENCES].body != NULL) {
2000                 if (compose->mode == COMPOSE_REEDIT)
2001                         compose->references = hentry[H_REFERENCES].body;
2002                 else {
2003                         compose->references = compose_parse_references
2004                                 (hentry[H_REFERENCES].body, msginfo->msgid);
2005                         g_free(hentry[H_REFERENCES].body);
2006                 }
2007                 hentry[H_REFERENCES].body = NULL;
2008         }
2009         if (hentry[H_BCC].body != NULL) {
2010                 if (compose->mode == COMPOSE_REEDIT)
2011                         compose->bcc =
2012                                 conv_unmime_header(hentry[H_BCC].body, NULL);
2013                 g_free(hentry[H_BCC].body);
2014                 hentry[H_BCC].body = NULL;
2015         }
2016         if (hentry[H_NEWSGROUPS].body != NULL) {
2017                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
2018                 hentry[H_NEWSGROUPS].body = NULL;
2019         }
2020         if (hentry[H_FOLLOWUP_TO].body != NULL) {
2021                 if (hentry[H_FOLLOWUP_TO].body[0] != '\0') {
2022                         compose->followup_to =
2023                                 conv_unmime_header(hentry[H_FOLLOWUP_TO].body,
2024                                                    NULL);
2025                 }
2026                 g_free(hentry[H_FOLLOWUP_TO].body);
2027                 hentry[H_FOLLOWUP_TO].body = NULL;
2028         }
2029         if (hentry[H_LIST_POST].body != NULL) {
2030                 gchar *to = NULL;
2031
2032                 extract_address(hentry[H_LIST_POST].body);
2033                 if (hentry[H_LIST_POST].body[0] != '\0') {
2034                         scan_mailto_url(hentry[H_LIST_POST].body,
2035                                         &to, NULL, NULL, NULL, NULL);
2036                         if (to) {
2037                                 g_free(compose->ml_post);
2038                                 compose->ml_post = to;
2039                         }
2040                 }
2041                 g_free(hentry[H_LIST_POST].body);
2042                 hentry[H_LIST_POST].body = NULL;
2043         }
2044
2045         /* CLAWS - X-Priority */
2046         if (compose->mode == COMPOSE_REEDIT)
2047                 if (hentry[H_X_PRIORITY].body != NULL) {
2048                         gint priority;
2049                         
2050                         priority = atoi(hentry[H_X_PRIORITY].body);
2051                         g_free(hentry[H_X_PRIORITY].body);
2052                         
2053                         hentry[H_X_PRIORITY].body = NULL;
2054                         
2055                         if (priority < PRIORITY_HIGHEST || 
2056                             priority > PRIORITY_LOWEST)
2057                                 priority = PRIORITY_NORMAL;
2058                         
2059                         compose->priority =  priority;
2060                 }
2061  
2062         if (compose->mode == COMPOSE_REEDIT) {
2063                 if (msginfo->inreplyto && *msginfo->inreplyto)
2064                         compose->inreplyto = g_strdup(msginfo->inreplyto);
2065                 return 0;
2066         }
2067
2068         if (msginfo->msgid && *msginfo->msgid)
2069                 compose->inreplyto = g_strdup(msginfo->msgid);
2070
2071         if (!compose->references) {
2072                 if (msginfo->msgid && *msginfo->msgid) {
2073                         if (msginfo->inreplyto && *msginfo->inreplyto)
2074                                 compose->references =
2075                                         g_strdup_printf("<%s>\n\t<%s>",
2076                                                         msginfo->inreplyto,
2077                                                         msginfo->msgid);
2078                         else
2079                                 compose->references =
2080                                         g_strconcat("<", msginfo->msgid, ">",
2081                                                     NULL);
2082                 } else if (msginfo->inreplyto && *msginfo->inreplyto) {
2083                         compose->references =
2084                                 g_strconcat("<", msginfo->inreplyto, ">",
2085                                             NULL);
2086                 }
2087         }
2088
2089         return 0;
2090 }
2091
2092 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
2093 {
2094         GSList *ref_id_list, *cur;
2095         GString *new_ref;
2096         gchar *new_ref_str;
2097
2098         ref_id_list = references_list_append(NULL, ref);
2099         if (!ref_id_list) return NULL;
2100         if (msgid && *msgid)
2101                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
2102
2103         for (;;) {
2104                 gint len = 0;
2105
2106                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
2107                         /* "<" + Message-ID + ">" + CR+LF+TAB */
2108                         len += strlen((gchar *)cur->data) + 5;
2109
2110                 if (len > MAX_REFERENCES_LEN) {
2111                         /* remove second message-ID */
2112                         if (ref_id_list && ref_id_list->next &&
2113                             ref_id_list->next->next) {
2114                                 g_free(ref_id_list->next->data);
2115                                 ref_id_list = g_slist_remove
2116                                         (ref_id_list, ref_id_list->next->data);
2117                         } else {
2118                                 slist_free_strings(ref_id_list);
2119                                 g_slist_free(ref_id_list);
2120                                 return NULL;
2121                         }
2122                 } else
2123                         break;
2124         }
2125
2126         new_ref = g_string_new("");
2127         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
2128                 if (new_ref->len > 0)
2129                         g_string_append(new_ref, "\n\t");
2130                 g_string_append_printf(new_ref, "<%s>", (gchar *)cur->data);
2131         }
2132
2133         slist_free_strings(ref_id_list);
2134         g_slist_free(ref_id_list);
2135
2136         new_ref_str = new_ref->str;
2137         g_string_free(new_ref, FALSE);
2138
2139         return new_ref_str;
2140 }
2141
2142 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
2143                                 const gchar *fmt, const gchar *qmark,
2144                                 const gchar *body, gboolean rewrap)
2145 {
2146         static MsgInfo dummyinfo;
2147         gchar *quote_str = NULL;
2148         gchar *buf;
2149         gboolean prev_autowrap;
2150         const gchar *trimmed_body = body;
2151         gint cursor_pos = -1;
2152         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2153         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2154         GtkTextIter iter;
2155         GtkTextMark *mark;
2156         
2157
2158         SIGNAL_BLOCK(buffer);
2159
2160         if (!msginfo)
2161                 msginfo = &dummyinfo;
2162
2163         if (qmark != NULL) {
2164                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
2165                 quote_fmt_scan_string(qmark);
2166                 quote_fmt_parse();
2167
2168                 buf = quote_fmt_get_buffer();
2169                 if (buf == NULL)
2170                         alertpanel_error(_("Quote mark format error."));
2171                 else
2172                         Xstrdup_a(quote_str, buf, goto error)
2173         }
2174
2175         if (fmt && *fmt != '\0') {
2176                 while (trimmed_body && strlen(trimmed_body) > 1
2177                         && trimmed_body[0]=='\n')
2178                         *trimmed_body++;
2179
2180                 quote_fmt_init(msginfo, quote_str, trimmed_body, FALSE);
2181                 quote_fmt_scan_string(fmt);
2182                 quote_fmt_parse();
2183
2184                 buf = quote_fmt_get_buffer();
2185                 if (buf == NULL) {
2186                         alertpanel_error(_("Message reply/forward format error."));
2187                         goto error;
2188                 }
2189         } else
2190                 buf = "";
2191
2192         prev_autowrap = compose->autowrap;
2193         compose->autowrap = FALSE;
2194
2195         mark = gtk_text_buffer_get_insert(buffer);
2196         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2197         if (g_utf8_validate(buf, -1, NULL)) { 
2198                 gtk_text_buffer_insert(buffer, &iter, buf, -1);
2199         } else {
2200                 gchar *tmpout = NULL;
2201                 tmpout = conv_codeset_strdup
2202                         (buf, conv_get_locale_charset_str(),
2203                          CS_INTERNAL);
2204                 if (!tmpout || !g_utf8_validate(tmpout, -1, NULL)) {
2205                         g_free(tmpout);
2206                         tmpout = g_malloc(strlen(buf)*2+1);
2207                         conv_localetodisp(tmpout, strlen(buf)*2+1, buf);
2208                 }
2209                 gtk_text_buffer_insert(buffer, &iter, tmpout, -1);
2210                 g_free(tmpout);
2211         }
2212
2213         cursor_pos = quote_fmt_get_cursor_pos();
2214         compose->set_cursor_pos = cursor_pos;
2215         if (cursor_pos == -1) {
2216                 cursor_pos = 0;
2217         }
2218         gtk_text_buffer_get_start_iter(buffer, &iter);
2219         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cursor_pos);
2220         gtk_text_buffer_place_cursor(buffer, &iter);
2221
2222         compose->autowrap = prev_autowrap;
2223         if (compose->autowrap && rewrap)
2224                 compose_wrap_all(compose);
2225
2226         goto ok;
2227
2228 error:
2229         buf = NULL;
2230 ok:
2231         SIGNAL_UNBLOCK(buffer);
2232
2233
2234         return buf;
2235 }
2236
2237 /* if ml_post is of type addr@host and from is of type
2238  * addr-anything@host, return TRUE
2239  */
2240 static gboolean is_subscription(const gchar *ml_post, const gchar *from)
2241 {
2242         gchar *left_ml = NULL;
2243         gchar *right_ml = NULL;
2244         gchar *left_from = NULL;
2245         gchar *right_from = NULL;
2246         gboolean result = FALSE;
2247         
2248         if (!ml_post || !from)
2249                 return FALSE;
2250         
2251         left_ml = g_strdup(ml_post);
2252         if (strstr(left_ml, "@")) {
2253                 right_ml = strstr(left_ml, "@")+1;
2254                 *(strstr(left_ml, "@")) = '\0';
2255         }
2256         
2257         left_from = g_strdup(from);
2258         if (strstr(left_from, "@")) {
2259                 right_from = strstr(left_from, "@")+1;
2260                 *(strstr(left_from, "@")) = '\0';
2261         }
2262         
2263         if (left_ml && left_from && right_ml && right_from
2264         &&  !strncmp(left_from, left_ml, strlen(left_ml))
2265         &&  !strcmp(right_from, right_ml)) {
2266                 result = TRUE;
2267         }
2268         g_free(left_ml);
2269         g_free(left_from);
2270         
2271         return result;
2272 }
2273
2274 static gboolean same_address(const gchar *addr1, const gchar *addr2)
2275 {
2276         gchar *my_addr1, *my_addr2;
2277         
2278         if (!addr1 || !addr2)
2279                 return FALSE;
2280
2281         Xstrdup_a(my_addr1, addr1, return FALSE);
2282         Xstrdup_a(my_addr2, addr2, return FALSE);
2283         
2284         extract_address(my_addr1);
2285         extract_address(my_addr2);
2286         
2287         return !strcmp(my_addr1, my_addr2);
2288 }
2289
2290 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
2291                                     gboolean to_all, gboolean to_ml,
2292                                     gboolean to_sender,
2293                                     gboolean followup_and_reply_to)
2294 {
2295         GSList *cc_list = NULL;
2296         GSList *cur;
2297         gchar *from = NULL;
2298         gchar *replyto = NULL;
2299         GHashTable *to_table;
2300
2301         gboolean reply_to_ml = FALSE;
2302         gboolean default_reply_to = FALSE;
2303
2304         g_return_if_fail(compose->account != NULL);
2305         g_return_if_fail(msginfo != NULL);
2306
2307         reply_to_ml = to_ml && compose->ml_post;
2308
2309         default_reply_to = msginfo->folder && 
2310                 msginfo->folder->prefs->enable_default_reply_to;
2311
2312         if (compose->account->protocol != A_NNTP) {
2313                 if (reply_to_ml && !default_reply_to) {
2314                         
2315                         gboolean is_subscr = is_subscription(compose->ml_post,
2316                                                              msginfo->from);
2317                         if (!is_subscr) {
2318                                 /* normal answer to ml post with a reply-to */
2319                                 compose_entry_append(compose,
2320                                            compose->ml_post,
2321                                            COMPOSE_TO);
2322                                 if (compose->replyto
2323                                 &&  !same_address(compose->ml_post, compose->replyto))
2324                                         compose_entry_append(compose,
2325                                                 compose->replyto,
2326                                                 COMPOSE_CC);
2327                         } else {
2328                                 /* answer to subscription confirmation */
2329                                 if (compose->replyto)
2330                                         compose_entry_append(compose,
2331                                                 compose->replyto,
2332                                                 COMPOSE_TO);
2333                                 else if (msginfo->from)
2334                                         compose_entry_append(compose,
2335                                                 msginfo->from,
2336                                                 COMPOSE_TO);
2337                         }
2338                 }
2339                 else if (!(to_all || to_sender) && default_reply_to) {
2340                         compose_entry_append(compose,
2341                             msginfo->folder->prefs->default_reply_to,
2342                             COMPOSE_TO);
2343                         compose_entry_mark_default_to(compose,
2344                                 msginfo->folder->prefs->default_reply_to);
2345                 } else {
2346                         gchar *tmp1 = NULL;
2347                         Xstrdup_a(tmp1, msginfo->from, return);
2348                         extract_address(tmp1);
2349                         if (to_all || to_sender ||
2350                             !account_find_from_address(tmp1))
2351                                 compose_entry_append(compose,
2352                                  (compose->replyto && !to_sender)
2353                                           ? compose->replyto :
2354                                           msginfo->from ? msginfo->from : "",
2355                                           COMPOSE_TO);
2356                         else if (!to_all && !to_sender) {
2357                                 /* reply to the last list of recipients */
2358                                 compose_entry_append(compose,
2359                                           msginfo->to ? msginfo->to : "",
2360                                           COMPOSE_TO);
2361                                 compose_entry_append(compose,
2362                                           msginfo->cc ? msginfo->cc : "",
2363                                           COMPOSE_CC);
2364                         }
2365                 }
2366         } else {
2367                 if (to_sender || (compose->followup_to && 
2368                         !strncmp(compose->followup_to, "poster", 6)))
2369                         compose_entry_append
2370                                 (compose, 
2371                                  (compose->replyto ? compose->replyto :
2372                                         msginfo->from ? msginfo->from : ""),
2373                                  COMPOSE_TO);
2374                                  
2375                 else if (followup_and_reply_to || to_all) {
2376                         compose_entry_append
2377                                 (compose,
2378                                  (compose->replyto ? compose->replyto :
2379                                  msginfo->from ? msginfo->from : ""),
2380                                  COMPOSE_TO);                           
2381                 
2382                         compose_entry_append
2383                                 (compose,
2384                                  compose->followup_to ? compose->followup_to :
2385                                  compose->newsgroups ? compose->newsgroups : "",
2386                                  COMPOSE_NEWSGROUPS);
2387                 } 
2388                 else 
2389                         compose_entry_append
2390                                 (compose,
2391                                  compose->followup_to ? compose->followup_to :
2392                                  compose->newsgroups ? compose->newsgroups : "",
2393                                  COMPOSE_NEWSGROUPS);
2394         }
2395
2396         if (msginfo->subject && *msginfo->subject) {
2397                 gchar *buf, *buf2;
2398                 guchar *p;
2399
2400                 buf = p = g_strdup(msginfo->subject);
2401                 p += subject_get_prefix_length(p);
2402                 memmove(buf, p, strlen(p) + 1);
2403
2404                 buf2 = g_strdup_printf("Re: %s", buf);
2405                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
2406
2407                 g_free(buf2);
2408                 g_free(buf);
2409         } else
2410                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
2411
2412         if (to_ml && compose->ml_post) return;
2413         if (!to_all || compose->account->protocol == A_NNTP) return;
2414
2415         if (compose->replyto) {
2416                 Xstrdup_a(replyto, compose->replyto, return);
2417                 extract_address(replyto);
2418         }
2419         if (msginfo->from) {
2420                 Xstrdup_a(from, msginfo->from, return);
2421                 extract_address(from);
2422         }
2423
2424         if (replyto && from)
2425                 cc_list = address_list_append_with_comments(cc_list, from);
2426         if (to_all && msginfo->folder && 
2427             msginfo->folder->prefs->enable_default_reply_to)
2428                 cc_list = address_list_append_with_comments(cc_list,
2429                                 msginfo->folder->prefs->default_reply_to);
2430         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
2431         cc_list = address_list_append_with_comments(cc_list, compose->cc);
2432
2433         to_table = g_hash_table_new(g_str_hash, g_str_equal);
2434         if (replyto)
2435                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
2436         if (compose->account)
2437                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
2438                                     GINT_TO_POINTER(1));
2439
2440         /* remove address on To: and that of current account */
2441         for (cur = cc_list; cur != NULL; ) {
2442                 GSList *next = cur->next;
2443                 gchar *addr;
2444
2445                 addr = g_strdup(cur->data);
2446                 extract_address(addr);
2447
2448                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
2449                         cc_list = g_slist_remove(cc_list, cur->data);
2450                 else
2451                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
2452
2453                 cur = next;
2454         }
2455         hash_free_strings(to_table);
2456         g_hash_table_destroy(to_table);
2457
2458         if (cc_list) {
2459                 for (cur = cc_list; cur != NULL; cur = cur->next)
2460                         compose_entry_append(compose, (gchar *)cur->data,
2461                                              COMPOSE_CC);
2462                 slist_free_strings(cc_list);
2463                 g_slist_free(cc_list);
2464         }
2465
2466 }
2467
2468 #define SET_ENTRY(entry, str) \
2469 { \
2470         if (str && *str) \
2471                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
2472 }
2473
2474 #define SET_ADDRESS(type, str) \
2475 { \
2476         if (str && *str) \
2477                 compose_entry_append(compose, str, type); \
2478 }
2479
2480 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
2481 {
2482         g_return_if_fail(msginfo != NULL);
2483
2484         SET_ENTRY(subject_entry, msginfo->subject);
2485         SET_ADDRESS(COMPOSE_TO, msginfo->to);
2486         SET_ADDRESS(COMPOSE_CC, compose->cc);
2487         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
2488         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
2489         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
2490         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2491
2492         compose_update_priority_menu_item(compose);
2493         compose_update_privacy_system_menu_item(compose, FALSE);
2494         compose_show_first_last_header(compose, TRUE);
2495 }
2496
2497 #undef SET_ENTRY
2498 #undef SET_ADDRESS
2499
2500 static void compose_insert_sig(Compose *compose, gboolean replace)
2501 {
2502         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2503         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2504         GtkTextMark *mark;
2505         GtkTextIter iter, iter_end;
2506         gint cur_pos;
2507         gboolean prev_autowrap;
2508
2509         
2510         g_return_if_fail(compose->account != NULL);
2511
2512         prev_autowrap = compose->autowrap;
2513         compose->autowrap = FALSE;
2514
2515         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2516                                         G_CALLBACK(compose_changed_cb),
2517                                         compose);
2518         
2519         mark = gtk_text_buffer_get_insert(buffer);
2520         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2521         cur_pos = gtk_text_iter_get_offset (&iter);
2522
2523         gtk_text_buffer_get_end_iter(buffer, &iter);
2524
2525         if (replace && compose->sig_str) {
2526                 gboolean found;
2527                 GtkTextIter first_iter, start_iter, end_iter;
2528
2529                 gtk_text_buffer_get_start_iter(buffer, &first_iter);
2530
2531                 if (compose->sig_str[0] == '\0')
2532                         found = FALSE;
2533                 else
2534                         found = gtk_text_iter_forward_search(&first_iter,
2535                                                              compose->sig_str,
2536                                                              GTK_TEXT_SEARCH_TEXT_ONLY,
2537                                                              &start_iter, &end_iter,
2538                                                              NULL);
2539
2540                 if (found) {
2541                         gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
2542                         iter = start_iter;
2543                 }
2544         }
2545
2546         g_free(compose->sig_str);
2547         compose->sig_str = compose_get_signature_str(compose);
2548         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2549                 compose->sig_str = g_strdup("");
2550
2551         cur_pos = gtk_text_iter_get_offset(&iter);
2552         gtk_text_buffer_insert(buffer, &iter, compose->sig_str, -1);
2553         /* skip \n\n */
2554         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2555         gtk_text_iter_forward_char(&iter);
2556         gtk_text_iter_forward_char(&iter);
2557         gtk_text_buffer_get_end_iter(buffer, &iter_end);
2558         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &iter_end);
2559
2560         if (cur_pos > gtk_text_buffer_get_char_count (buffer))
2561                 cur_pos = gtk_text_buffer_get_char_count (buffer);
2562
2563         /* put the cursor where it should be 
2564          * either where the quote_fmt says, either before the signature */
2565         if (compose->set_cursor_pos < 0)
2566                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2567         else
2568                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, 
2569                         compose->set_cursor_pos);
2570                 
2571         gtk_text_buffer_place_cursor(buffer, &iter);
2572         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2573                                         G_CALLBACK(compose_changed_cb),
2574                                         compose);
2575                 
2576         compose->autowrap = prev_autowrap;
2577         if (compose->autowrap)
2578                 compose_wrap_all(compose);
2579 }
2580
2581 static gchar *compose_get_signature_str(Compose *compose)
2582 {
2583         gchar *sig_body = NULL;
2584         gchar *sig_str = NULL;
2585         gchar *utf8_sig_str = NULL;
2586
2587         g_return_val_if_fail(compose->account != NULL, NULL);
2588
2589         if (!compose->account->sig_path)
2590                 return NULL;
2591
2592         if (compose->account->sig_type == SIG_FILE) {
2593                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2594                         g_warning("can't open signature file: %s\n",
2595                                   compose->account->sig_path);
2596                         return NULL;
2597                 }
2598         }
2599
2600         if (compose->account->sig_type == SIG_COMMAND)
2601                 sig_body = get_command_output(compose->account->sig_path);
2602         else {
2603                 gchar *tmp;
2604
2605                 tmp = file_read_to_str(compose->account->sig_path);
2606                 if (!tmp)
2607                         return NULL;
2608                 sig_body = normalize_newlines(tmp);
2609                 g_free(tmp);
2610         }
2611
2612         if (compose->account->sig_sep) {
2613                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2614                                       NULL);
2615                 g_free(sig_body);
2616         } else
2617                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2618
2619         if (sig_str) {
2620                 if (g_utf8_validate(sig_str, -1, NULL) == TRUE)
2621                         utf8_sig_str = sig_str;
2622                 else {
2623                         utf8_sig_str = conv_codeset_strdup
2624                                 (sig_str, conv_get_locale_charset_str(),
2625                                  CS_INTERNAL);
2626                         g_free(sig_str);
2627                 }
2628         }
2629
2630         return utf8_sig_str;
2631 }
2632
2633 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2634 {
2635         GtkTextView *text;
2636         GtkTextBuffer *buffer;
2637         GtkTextMark *mark;
2638         GtkTextIter iter;
2639         const gchar *cur_encoding;
2640         gchar buf[BUFFSIZE];
2641         gint len;
2642         FILE *fp;
2643         gboolean prev_autowrap;
2644         gboolean badtxt = FALSE;
2645
2646         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2647
2648         if ((fp = g_fopen(file, "rb")) == NULL) {
2649                 FILE_OP_ERROR(file, "fopen");
2650                 return COMPOSE_INSERT_READ_ERROR;
2651         }
2652
2653         prev_autowrap = compose->autowrap;
2654         compose->autowrap = FALSE;
2655
2656         text = GTK_TEXT_VIEW(compose->text);
2657         buffer = gtk_text_view_get_buffer(text);
2658         mark = gtk_text_buffer_get_insert(buffer);
2659         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2660
2661         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2662                                         G_CALLBACK(text_inserted),
2663                                         compose);
2664
2665         cur_encoding = conv_get_locale_charset_str();
2666
2667         while (fgets(buf, sizeof(buf), fp) != NULL) {
2668                 gchar *str;
2669
2670                 if (g_utf8_validate(buf, -1, NULL) == TRUE)
2671                         str = g_strdup(buf);
2672                 else
2673                         str = conv_codeset_strdup
2674                                 (buf, cur_encoding, CS_INTERNAL);
2675                 if (!str) continue;
2676
2677                 /* strip <CR> if DOS/Windows file,
2678                    replace <CR> with <LF> if Macintosh file. */
2679                 strcrchomp(str);
2680                 len = strlen(str);
2681                 if (len > 0 && str[len - 1] != '\n') {
2682                         while (--len >= 0)
2683                                 if (str[len] == '\r') str[len] = '\n';
2684                 }
2685
2686                 gtk_text_buffer_insert(buffer, &iter, str, -1);
2687                 g_free(str);
2688         }
2689
2690         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2691                                           G_CALLBACK(text_inserted),
2692                                           compose);
2693         compose->autowrap = prev_autowrap;
2694         if (compose->autowrap)
2695                 compose_wrap_all(compose);
2696
2697         fclose(fp);
2698
2699         if (badtxt)
2700                 return COMPOSE_INSERT_INVALID_CHARACTER;
2701         else 
2702                 return COMPOSE_INSERT_SUCCESS;
2703 }
2704
2705 static void compose_attach_append(Compose *compose, const gchar *file,
2706                                   const gchar *filename,
2707                                   const gchar *content_type)
2708 {
2709         AttachInfo *ainfo;
2710         GtkTreeIter iter;
2711         FILE *fp;
2712         off_t size;
2713         GAuto *auto_ainfo;
2714         gchar *size_text;
2715         GtkListStore *store;
2716         gchar *name;
2717
2718         if (!is_file_exist(file)) {
2719                 g_warning("File %s doesn't exist\n", filename);
2720                 return;
2721         }
2722         if ((size = get_file_size(file)) < 0) {
2723                 g_warning("Can't get file size of %s\n", filename);
2724                 return;
2725         }
2726         if (size == 0) {
2727                 alertpanel_notice(_("File %s is empty."), filename);
2728                 return;
2729         }
2730         if ((fp = g_fopen(file, "rb")) == NULL) {
2731                 alertpanel_error(_("Can't read %s."), filename);
2732                 return;
2733         }
2734         fclose(fp);
2735
2736         ainfo = g_new0(AttachInfo, 1);
2737         auto_ainfo = g_auto_pointer_new_with_free
2738                         (ainfo, (GFreeFunc) compose_attach_info_free); 
2739         ainfo->file = g_strdup(file);
2740
2741         if (content_type) {
2742                 ainfo->content_type = g_strdup(content_type);
2743                 if (!g_ascii_strcasecmp(content_type, "message/rfc822")) {
2744                         MsgInfo *msginfo;
2745                         MsgFlags flags = {0, 0};
2746
2747                         if (procmime_get_encoding_for_text_file(file) == ENC_7BIT)
2748                                 ainfo->encoding = ENC_7BIT;
2749                         else
2750                                 ainfo->encoding = ENC_8BIT;
2751
2752                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2753                         if (msginfo && msginfo->subject)
2754                                 name = g_strdup(msginfo->subject);
2755                         else
2756                                 name = g_path_get_basename(filename ? filename : file);
2757
2758                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2759
2760                         procmsg_msginfo_free(msginfo);
2761                 } else {
2762                         if (!g_ascii_strncasecmp(content_type, "text", 4))
2763                                 ainfo->encoding = procmime_get_encoding_for_text_file(file);
2764                         else
2765                                 ainfo->encoding = ENC_BASE64;
2766                         name = g_path_get_basename(filename ? filename : file);
2767                         ainfo->name = g_strdup(name);
2768                 }
2769                 g_free(name);
2770         } else {
2771                 ainfo->content_type = procmime_get_mime_type(file);
2772                 if (!ainfo->content_type) {
2773                         ainfo->content_type =
2774                                 g_strdup("application/octet-stream");
2775                         ainfo->encoding = ENC_BASE64;
2776                 } else if (!g_ascii_strncasecmp(ainfo->content_type, "text", 4))
2777                         ainfo->encoding =
2778                                 procmime_get_encoding_for_text_file(file);
2779                 else
2780                         ainfo->encoding = ENC_BASE64;
2781                 name = g_path_get_basename(filename ? filename : file);
2782                 ainfo->name = g_strdup(name);   
2783                 g_free(name);
2784         }
2785
2786         if (!strcmp(ainfo->content_type, "unknown")) {
2787                 g_free(ainfo->content_type);
2788                 ainfo->content_type = g_strdup("application/octet-stream");
2789         }
2790
2791         ainfo->size = size;
2792         size_text = to_human_readable(size);
2793
2794         store = GTK_LIST_STORE(gtk_tree_view_get_model
2795                         (GTK_TREE_VIEW(compose->attach_clist)));
2796                 
2797         gtk_list_store_append(store, &iter);
2798         gtk_list_store_set(store, &iter, 
2799                            COL_MIMETYPE, ainfo->content_type,
2800                            COL_SIZE, size_text,
2801                            COL_NAME, ainfo->name,
2802                            COL_DATA, ainfo,
2803                            COL_AUTODATA, auto_ainfo,
2804                            -1);
2805         
2806         g_auto_pointer_free(auto_ainfo);
2807 }
2808
2809 static void compose_use_signing(Compose *compose, gboolean use_signing)
2810 {
2811         GtkItemFactory *ifactory;
2812         GtkWidget *menuitem = NULL;
2813
2814         compose->use_signing = use_signing;
2815         ifactory = gtk_item_factory_from_widget(compose->menubar);
2816         menuitem = gtk_item_factory_get_item
2817                 (ifactory, "/Options/Sign");
2818         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2819                                        use_signing);
2820 }
2821
2822 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2823 {
2824         GtkItemFactory *ifactory;
2825         GtkWidget *menuitem = NULL;
2826
2827         compose->use_encryption = use_encryption;
2828         ifactory = gtk_item_factory_from_widget(compose->menubar);
2829         menuitem = gtk_item_factory_get_item
2830                 (ifactory, "/Options/Encrypt");
2831
2832         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2833                                        use_encryption);
2834 }
2835
2836 #define NEXT_PART_NOT_CHILD(info)  \
2837 {  \
2838         node = info->node;  \
2839         while (node->children)  \
2840                 node = g_node_last_child(node);  \
2841         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2842 }
2843
2844 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2845 {
2846         MimeInfo *mimeinfo;
2847         MimeInfo *child;
2848         MimeInfo *firsttext = NULL;
2849         MimeInfo *encrypted = NULL;
2850         GNode    *node;
2851         gchar *outfile;
2852         const gchar *partname = NULL;
2853
2854         mimeinfo = procmime_scan_message(msginfo);
2855         if (!mimeinfo) return;
2856
2857         if (mimeinfo->node->children == NULL) {
2858                 procmime_mimeinfo_free_all(mimeinfo);
2859                 return;
2860         }
2861
2862         /* find first content part */
2863         child = (MimeInfo *) mimeinfo->node->children->data;
2864         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2865                 child = (MimeInfo *)child->node->children->data;
2866
2867         if (child->type == MIMETYPE_TEXT) {
2868                 firsttext = child;
2869                 debug_print("First text part found\n");
2870         } else if (compose->mode == COMPOSE_REEDIT &&
2871                  child->type == MIMETYPE_APPLICATION &&
2872                  !g_ascii_strcasecmp(child->subtype, "pgp-encrypted")) {
2873                 encrypted = (MimeInfo *)child->node->parent->data;
2874         }
2875      
2876         child = (MimeInfo *) mimeinfo->node->children->data;
2877         while (child != NULL) {
2878                 if (child == encrypted) {
2879                         /* skip this part of tree */
2880                         NEXT_PART_NOT_CHILD(child);
2881                         continue;
2882                 }
2883
2884                 if (child->type == MIMETYPE_MULTIPART) {
2885                         /* get the actual content */
2886                         child = procmime_mimeinfo_next(child);
2887                         continue;
2888                 }
2889                     
2890                 if (child == firsttext) {
2891                         child = procmime_mimeinfo_next(child);
2892                         continue;
2893                 }
2894
2895                 outfile = procmime_get_tmp_file_name(child);
2896                 if (procmime_get_part(outfile, child) < 0)
2897                         g_warning("Can't get the part of multipart message.");
2898                 else {
2899                         gchar *content_type;
2900
2901                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2902
2903                         /* if we meet a pgp signature, we don't attach it, but
2904                          * we force signing. */
2905                         if (strcmp(content_type, "application/pgp-signature")) {
2906                                 partname = procmime_mimeinfo_get_parameter(child, "filename");
2907                                 if (partname == NULL)
2908                                         partname = procmime_mimeinfo_get_parameter(child, "name");
2909                                 if (partname == NULL)
2910                                         partname = "";
2911                                 compose_attach_append(compose, outfile, 
2912                                                       partname, content_type);
2913                         } else {
2914                                 compose_force_signing(compose, compose->account);
2915                         }
2916                         g_free(content_type);
2917                 }
2918                 g_free(outfile);
2919                 NEXT_PART_NOT_CHILD(child);
2920         }
2921         procmime_mimeinfo_free_all(mimeinfo);
2922 }
2923
2924 #undef NEXT_PART_NOT_CHILD
2925
2926
2927
2928 typedef enum {
2929         WAIT_FOR_INDENT_CHAR,
2930         WAIT_FOR_INDENT_CHAR_OR_SPACE,
2931 } IndentState;
2932
2933 /* return indent length, we allow:
2934    indent characters followed by indent characters or spaces/tabs,
2935    alphabets and numbers immediately followed by indent characters,
2936    and the repeating sequences of the above
2937    If quote ends with multiple spaces, only the first one is included. */
2938 static gchar *compose_get_quote_str(GtkTextBuffer *buffer,
2939                                     const GtkTextIter *start, gint *len)
2940 {
2941         GtkTextIter iter = *start;
2942         gunichar wc;
2943         gchar ch[6];
2944         gint clen;
2945         IndentState state = WAIT_FOR_INDENT_CHAR;
2946         gboolean is_space;
2947         gboolean is_indent;
2948         gint alnum_count = 0;
2949         gint space_count = 0;
2950         gint quote_len = 0;
2951
2952         if (prefs_common.quote_chars == NULL) {
2953                 return 0 ;
2954         }
2955
2956         while (!gtk_text_iter_ends_line(&iter)) {
2957                 wc = gtk_text_iter_get_char(&iter);
2958                 if (g_unichar_iswide(wc))
2959                         break;
2960                 clen = g_unichar_to_utf8(wc, ch);
2961                 if (clen != 1)
2962                         break;
2963
2964                 is_indent = strchr(prefs_common.quote_chars, ch[0]) ? TRUE : FALSE;
2965                 is_space = g_unichar_isspace(wc);
2966
2967                 if (state == WAIT_FOR_INDENT_CHAR) {
2968                         if (!is_indent && !g_unichar_isalnum(wc))
2969                                 break;
2970                         if (is_indent) {
2971                                 quote_len += alnum_count + space_count + 1;
2972                                 alnum_count = space_count = 0;
2973                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2974                         } else
2975                                 alnum_count++;
2976                 } else if (state == WAIT_FOR_INDENT_CHAR_OR_SPACE) {
2977                         if (!is_indent && !is_space && !g_unichar_isalnum(wc))
2978                                 break;
2979                         if (is_space)
2980                                 space_count++;
2981                         else if (is_indent) {
2982                                 quote_len += alnum_count + space_count + 1;
2983                                 alnum_count = space_count = 0;
2984                         } else {
2985                                 alnum_count++;
2986                                 state = WAIT_FOR_INDENT_CHAR;
2987                         }
2988                 }
2989
2990                 gtk_text_iter_forward_char(&iter);
2991         }
2992
2993         if (quote_len > 0 && space_count > 0)
2994                 quote_len++;
2995
2996         if (len)
2997                 *len = quote_len;
2998
2999         if (quote_len > 0) {
3000                 iter = *start;
3001                 gtk_text_iter_forward_chars(&iter, quote_len);
3002                 return gtk_text_buffer_get_text(buffer, start, &iter, FALSE);
3003         }
3004
3005         return NULL;
3006 }
3007
3008 /* return TRUE if the line is itemized */
3009 static gboolean compose_is_itemized(GtkTextBuffer *buffer,
3010                                     const GtkTextIter *start)
3011 {
3012         GtkTextIter iter = *start;
3013         gunichar wc;
3014         gchar ch[6];
3015         gint clen;
3016
3017         if (gtk_text_iter_ends_line(&iter))
3018                 return FALSE;
3019
3020         while (1) {
3021                 wc = gtk_text_iter_get_char(&iter);
3022                 if (!g_unichar_isspace(wc))
3023                         break;
3024                 gtk_text_iter_forward_char(&iter);
3025                 if (gtk_text_iter_ends_line(&iter))
3026                         return FALSE;
3027         }
3028
3029         clen = g_unichar_to_utf8(wc, ch);
3030         if (clen != 1)
3031                 return FALSE;
3032
3033         if (!strchr("*-+", ch[0]))
3034                 return FALSE;
3035
3036         gtk_text_iter_forward_char(&iter);
3037         if (gtk_text_iter_ends_line(&iter))
3038                 return FALSE;
3039         wc = gtk_text_iter_get_char(&iter);
3040         if (g_unichar_isspace(wc))
3041                 return TRUE;
3042
3043         return FALSE;
3044 }
3045
3046 static gboolean compose_get_line_break_pos(GtkTextBuffer *buffer,
3047                                            const GtkTextIter *start,
3048                                            GtkTextIter *break_pos,
3049                                            gint max_col,
3050                                            gint quote_len)
3051 {
3052         GtkTextIter iter = *start, line_end = *start;
3053         PangoLogAttr *attrs;
3054         gchar *str;
3055         gchar *p;
3056         gint len;
3057         gint i;
3058         gint col = 0;
3059         gint pos = 0;
3060         gboolean can_break = FALSE;
3061         gboolean do_break = FALSE;
3062         gboolean was_white = FALSE;
3063         gboolean prev_dont_break = FALSE;
3064
3065         gtk_text_iter_forward_to_line_end(&line_end);
3066         str = gtk_text_buffer_get_text(buffer, &iter, &line_end, FALSE);
3067         len = g_utf8_strlen(str, -1);
3068         /* g_print("breaking line: %d: %s (len = %d)\n",
3069                 gtk_text_iter_get_line(&iter), str, len); */
3070         attrs = g_new(PangoLogAttr, len + 1);
3071
3072         pango_default_break(str, -1, NULL, attrs, len + 1);
3073
3074         p = str;
3075
3076         /* skip quote and leading spaces */
3077         for (i = 0; *p != '\0' && i < len; i++) {
3078                 gunichar wc;
3079
3080                 wc = g_utf8_get_char(p);
3081                 if (i >= quote_len && !g_unichar_isspace(wc))
3082                         break;
3083                 if (g_unichar_iswide(wc))
3084                         col += 2;
3085                 else if (*p == '\t')
3086                         col += 8;
3087                 else
3088                         col++;
3089                 p = g_utf8_next_char(p);
3090         }
3091
3092         for (; *p != '\0' && i < len; i++) {
3093                 PangoLogAttr *attr = attrs + i;
3094                 gunichar wc;
3095                 gint uri_len;
3096
3097                 if (attr->is_line_break && can_break && was_white && !prev_dont_break)
3098                         pos = i;
3099                 
3100                 was_white = attr->is_white;
3101
3102                 /* don't wrap URI */
3103                 if ((uri_len = get_uri_len(p)) > 0) {
3104                         col += uri_len;
3105                         if (pos > 0 && col > max_col) {
3106                                 do_break = TRUE;
3107                                 break;
3108                         }
3109                         i += uri_len - 1;
3110                         p += uri_len;
3111                         can_break = TRUE;
3112                         continue;
3113                 }
3114
3115                 wc = g_utf8_get_char(p);
3116                 if (g_unichar_iswide(wc)) {
3117                         col += 2;
3118                         if (prev_dont_break && can_break && attr->is_line_break)
3119                                 pos = i;
3120                 } else if (*p == '\t')
3121                         col += 8;
3122                 else
3123                         col++;
3124                 if (pos > 0 && col > max_col) {
3125                         do_break = TRUE;
3126                         break;
3127                 }
3128
3129                 if (*p == '-' || *p == '/')
3130                         prev_dont_break = TRUE;
3131                 else
3132                         prev_dont_break = FALSE;
3133
3134                 p = g_utf8_next_char(p);
3135                 can_break = TRUE;
3136         }
3137
3138         debug_print("compose_get_line_break_pos(): do_break = %d, pos = %d, col = %d\n", do_break, pos, col);
3139
3140         g_free(attrs);
3141         g_free(str);
3142
3143         *break_pos = *start;
3144         gtk_text_iter_set_line_offset(break_pos, pos);
3145
3146         return do_break;
3147 }
3148
3149 static gboolean compose_join_next_line(Compose *compose,
3150                                        GtkTextBuffer *buffer,
3151                                        GtkTextIter *iter,
3152                                        const gchar *quote_str)
3153 {
3154         GtkTextIter iter_ = *iter, cur, prev, next, end;
3155         PangoLogAttr attrs[3];
3156         gchar *str;
3157         gchar *next_quote_str;
3158         gunichar wc1, wc2;
3159         gint quote_len;
3160         gboolean keep_cursor = FALSE;
3161
3162         if (!gtk_text_iter_forward_line(&iter_) ||
3163             gtk_text_iter_ends_line(&iter_))
3164                 return FALSE;
3165
3166         next_quote_str = compose_get_quote_str(buffer, &iter_, &quote_len);
3167
3168         if ((quote_str || next_quote_str) &&
3169             strcmp2(quote_str, next_quote_str) != 0) {
3170                 g_free(next_quote_str);
3171                 return FALSE;
3172         }
3173         g_free(next_quote_str);
3174
3175         end = iter_;
3176         if (quote_len > 0) {
3177                 gtk_text_iter_forward_chars(&end, quote_len);
3178                 if (gtk_text_iter_ends_line(&end))
3179                         return FALSE;
3180         }
3181
3182         /* don't join itemized lines */
3183         if (compose_is_itemized(buffer, &end))
3184                 return FALSE;
3185
3186         /* don't join signature separator */
3187         if (compose_is_sig_separator(compose, buffer, &iter_))
3188                 return FALSE;
3189
3190         /* delete quote str */
3191         if (quote_len > 0)
3192                 gtk_text_buffer_delete(buffer, &iter_, &end);
3193
3194         /* don't join line breaks put by the user */
3195         prev = cur = iter_;
3196         gtk_text_iter_backward_char(&cur);
3197         if (gtk_text_iter_has_tag(&cur, compose->no_join_tag)) {
3198                 gtk_text_iter_forward_char(&cur);
3199                 *iter = cur;
3200                 return FALSE;
3201         }
3202         gtk_text_iter_forward_char(&cur);
3203         /* delete linebreak and extra spaces */
3204         while (gtk_text_iter_backward_char(&cur)) {
3205                 wc1 = gtk_text_iter_get_char(&cur);
3206                 if (!g_unichar_isspace(wc1))
3207                         break;
3208                 prev = cur;
3209         }
3210         next = cur = iter_;
3211         while (!gtk_text_iter_ends_line(&cur)) {
3212                 wc1 = gtk_text_iter_get_char(&cur);
3213                 if (!g_unichar_isspace(wc1))
3214                         break;
3215                 gtk_text_iter_forward_char(&cur);
3216                 next = cur;
3217         }
3218         if (!gtk_text_iter_equal(&prev, &next)) {
3219                 GtkTextMark *mark;
3220
3221                 mark = gtk_text_buffer_get_insert(buffer);
3222                 gtk_text_buffer_get_iter_at_mark(buffer, &cur, mark);
3223                 if (gtk_text_iter_equal(&prev, &cur))
3224                         keep_cursor = TRUE;
3225                 gtk_text_buffer_delete(buffer, &prev, &next);
3226         }
3227         iter_ = prev;
3228
3229         /* insert space if required */
3230         gtk_text_iter_backward_char(&prev);
3231         wc1 = gtk_text_iter_get_char(&prev);
3232         wc2 = gtk_text_iter_get_char(&next);
3233         gtk_text_iter_forward_char(&next);
3234         str = gtk_text_buffer_get_text(buffer, &prev, &next, FALSE);
3235         pango_default_break(str, -1, NULL, attrs, 3);
3236         if (!attrs[1].is_line_break ||
3237             (!g_unichar_iswide(wc1) || !g_unichar_iswide(wc2))) {
3238                 gtk_text_buffer_insert(buffer, &iter_, " ", 1);
3239                 if (keep_cursor) {
3240                         gtk_text_iter_backward_char(&iter_);
3241                         gtk_text_buffer_place_cursor(buffer, &iter_);
3242                 }
3243         }
3244         g_free(str);
3245
3246         *iter = iter_;
3247         return TRUE;
3248 }
3249
3250 #define ADD_TXT_POS(bp_, ep_, pti_) \
3251         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
3252                 last = last->next; \
3253                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
3254                 last->next = NULL; \
3255         } else { \
3256                 g_warning("alloc error scanning URIs\n"); \
3257         }
3258
3259 static gboolean automatic_break = FALSE;
3260 static void compose_beautify_paragraph(Compose *compose, GtkTextIter *par_iter, gboolean force)
3261 {
3262         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3263         GtkTextBuffer *buffer;
3264         GtkTextIter iter, break_pos, end_of_line;
3265         gchar *quote_str = NULL;
3266         gint quote_len;
3267         gboolean wrap_quote = prefs_common.linewrap_quote;
3268         gboolean prev_autowrap = compose->autowrap;
3269         gint startq_offset = -1, noq_offset = -1;
3270         gint uri_start = -1, uri_stop = -1;
3271         gint nouri_start = -1, nouri_stop = -1;
3272
3273         compose->autowrap = FALSE;
3274
3275         buffer = gtk_text_view_get_buffer(text);
3276         undo_wrapping(compose->undostruct, TRUE);
3277         if (par_iter) {
3278                 iter = *par_iter;
3279         } else {
3280                 GtkTextMark *mark;
3281                 mark = gtk_text_buffer_get_insert(buffer);
3282                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
3283         }
3284
3285         /* move to paragraph start */
3286         gtk_text_iter_set_line_offset(&iter, 0);
3287         if (gtk_text_iter_ends_line(&iter)) {
3288                 while (gtk_text_iter_ends_line(&iter) &&
3289                        gtk_text_iter_forward_line(&iter))
3290                         ;
3291         } else {
3292                 while (gtk_text_iter_backward_line(&iter)) {
3293                         if (gtk_text_iter_ends_line(&iter)) {
3294                                 gtk_text_iter_forward_line(&iter);
3295                                 break;
3296                         }
3297                 }
3298         }
3299
3300         /* go until paragraph end (empty line) */
3301         
3302         while (!gtk_text_iter_ends_line(&iter)) {
3303                 gchar *scanpos = NULL;
3304                 /* parse table - in order of priority */
3305                 struct table {
3306                         const gchar *needle; /* token */
3307
3308                         /* token search function */
3309                         gchar    *(*search)     (const gchar *haystack,
3310                                                  const gchar *needle);
3311                         /* part parsing function */
3312                         gboolean  (*parse)      (const gchar *start,
3313                                                  const gchar *scanpos,
3314                                                  const gchar **bp_,
3315                                                  const gchar **ep_,
3316                                                  gboolean hdr);
3317                         /* part to URI function */
3318                         gchar    *(*build_uri)  (const gchar *bp,
3319                                                  const gchar *ep);
3320                 };
3321
3322                 static struct table parser[] = {
3323                         {"http://",  strcasestr, get_uri_part,   make_uri_string},
3324                         {"https://", strcasestr, get_uri_part,   make_uri_string},
3325                         {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
3326                         {"www.",     strcasestr, get_uri_part,   make_http_string},
3327                         {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
3328                         {"@",        strcasestr, get_email_part, make_email_string}
3329                 };
3330                 const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
3331                 gint last_index = PARSE_ELEMS;
3332                 gint  n;
3333                 gchar *o_walk = NULL, *walk = NULL, *bp = NULL, *ep = NULL;
3334                 gint walk_pos;
3335                 
3336                 if (!prev_autowrap)
3337                         g_signal_handlers_block_by_func(G_OBJECT(buffer),
3338                                         G_CALLBACK(text_inserted),
3339                                         compose);
3340                 
3341                 if (gtk_text_iter_has_tag(&iter, compose->no_wrap_tag) && !force)
3342                         goto colorize;
3343
3344                 uri_start = uri_stop = -1;
3345                 quote_len = 0;
3346                 quote_str = compose_get_quote_str(buffer, &iter, &quote_len);
3347
3348                 if (quote_str) {
3349                         if (!wrap_quote) {
3350                                 if (startq_offset == -1) {
3351                                         startq_offset = gtk_text_iter_get_offset(&iter);
3352                                 }
3353                                 goto colorize;
3354                         }
3355                         debug_print("compose_beautify_paragraph(): quote_str = '%s'\n", quote_str);
3356                         if (startq_offset == -1) 
3357                                 startq_offset = gtk_text_iter_get_offset(&iter);
3358                 } else {
3359                         if (startq_offset == -1)
3360                                 noq_offset = gtk_text_iter_get_offset(&iter);
3361                 }
3362
3363                 if (prev_autowrap == FALSE && !force && !wrap_quote) {
3364                         goto colorize;
3365                 }
3366                 if (compose_get_line_break_pos(buffer, &iter, &break_pos,
3367                                                prefs_common.linewrap_len,
3368                                                quote_len)) {
3369                         GtkTextIter prev, next, cur;
3370                         
3371                         if (prev_autowrap != FALSE || force) {
3372                                 automatic_break = TRUE;
3373                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3374                                 automatic_break = FALSE;
3375                         } else if (quote_str && wrap_quote) {
3376                                 automatic_break = TRUE;
3377                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3378                                 automatic_break = FALSE;
3379                         } else 
3380                                 goto colorize;
3381                         /* remove trailing spaces */
3382                         cur = break_pos;
3383                         gtk_text_iter_backward_char(&cur);
3384                         prev = next = cur;
3385                         while (!gtk_text_iter_starts_line(&cur)) {
3386                                 gunichar wc;
3387
3388                                 gtk_text_iter_backward_char(&cur);
3389                                 wc = gtk_text_iter_get_char(&cur);
3390                                 if (!g_unichar_isspace(wc))
3391                                         break;
3392                                 prev = cur;
3393                         }
3394                         if (!gtk_text_iter_equal(&prev, &next)) {
3395                                 gtk_text_buffer_delete(buffer, &prev, &next);
3396                                 break_pos = next;
3397                                 gtk_text_iter_forward_char(&break_pos);
3398                         }
3399
3400                         if (quote_str)
3401                                 gtk_text_buffer_insert(buffer, &break_pos,
3402                                                        quote_str, -1);
3403
3404                         iter = break_pos;
3405                         compose_join_next_line(compose, buffer, &iter, quote_str);
3406
3407                         /* move iter to current line start */
3408                         gtk_text_iter_set_line_offset(&iter, 0);
3409                         if (quote_str) {
3410                                 g_free(quote_str);
3411                                 quote_str = NULL;
3412                         }
3413                         continue;
3414                 } else {
3415                         /* move iter to next line start */
3416                         iter = break_pos;
3417                 }
3418
3419 colorize:
3420                 if (!prev_autowrap)
3421                         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
3422                                         G_CALLBACK(text_inserted),
3423                                         compose);
3424                 end_of_line = iter;
3425                 while (!gtk_text_iter_ends_line(&end_of_line)) {
3426                         gtk_text_iter_forward_char(&end_of_line);
3427                 }
3428                 o_walk = walk = gtk_text_buffer_get_text(buffer, &iter, &end_of_line, FALSE);
3429
3430                 nouri_start = gtk_text_iter_get_offset(&iter);
3431                 nouri_stop = gtk_text_iter_get_offset(&end_of_line);
3432
3433                 walk_pos = gtk_text_iter_get_offset(&iter);
3434                 /* FIXME: this looks phony. scanning for anything in the parse table */
3435                 for (n = 0; n < PARSE_ELEMS; n++) {
3436                         gchar *tmp;
3437
3438                         tmp = parser[n].search(walk, parser[n].needle);
3439                         if (tmp) {
3440                                 if (scanpos == NULL || tmp < scanpos) {
3441                                         scanpos = tmp;
3442                                         last_index = n;
3443                                 }
3444                         }                                       
3445                 }
3446
3447                 bp = ep = 0;
3448                 if (scanpos) {
3449                         /* check if URI can be parsed */
3450                         if (parser[last_index].parse(walk, scanpos, (const gchar **)&bp,
3451                                         (const gchar **)&ep, FALSE)
3452                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
3453                                         walk = ep;
3454                         } else
3455                                 walk = scanpos +
3456                                         strlen(parser[last_index].needle);
3457                 } 
3458                 if (bp && ep) {
3459                         uri_start = walk_pos + (bp - o_walk);
3460                         uri_stop  = walk_pos + (ep - o_walk);
3461                 }
3462                 g_free(o_walk);
3463                 o_walk = NULL;
3464                 gtk_text_iter_forward_line(&iter);
3465                 g_free(quote_str);
3466                 quote_str = NULL;
3467                 if (startq_offset != -1) {
3468                         GtkTextIter startquote, endquote;
3469                         gtk_text_buffer_get_iter_at_offset(
3470                                 buffer, &startquote, startq_offset);
3471                         endquote = iter;
3472                         gtk_text_buffer_apply_tag_by_name(
3473                                 buffer, "quote", &startquote, &endquote);
3474                         startq_offset = -1;
3475                 } else if (noq_offset != -1) {
3476                         GtkTextIter startnoquote, endnoquote;
3477                         gtk_text_buffer_get_iter_at_offset(
3478                                 buffer, &startnoquote, noq_offset);
3479                         endnoquote = iter;
3480                         gtk_text_buffer_remove_tag_by_name(
3481                                 buffer, "quote", &startnoquote, &endnoquote);
3482                         noq_offset = -1;
3483                 }
3484                 
3485                 /* always */ {
3486                         GtkTextIter nouri_start_iter, nouri_end_iter;
3487                         gtk_text_buffer_get_iter_at_offset(
3488                                 buffer, &nouri_start_iter, nouri_start);
3489                         gtk_text_buffer_get_iter_at_offset(
3490                                 buffer, &nouri_end_iter, nouri_stop);
3491                         gtk_text_buffer_remove_tag_by_name(
3492                                 buffer, "link", &nouri_start_iter, &nouri_end_iter);
3493                 }
3494                 if (uri_start > 0 && uri_stop > 0) {
3495                         GtkTextIter uri_start_iter, uri_end_iter;
3496                         gtk_text_buffer_get_iter_at_offset(
3497                                 buffer, &uri_start_iter, uri_start);
3498                         gtk_text_buffer_get_iter_at_offset(
3499                                 buffer, &uri_end_iter, uri_stop);
3500                         gtk_text_buffer_apply_tag_by_name(
3501                                 buffer, "link", &uri_start_iter, &uri_end_iter);
3502                 }
3503         }
3504
3505         if (par_iter)
3506                 *par_iter = iter;
3507         undo_wrapping(compose->undostruct, FALSE);
3508         compose->autowrap = prev_autowrap;
3509 }
3510
3511 void compose_action_cb(void *data)
3512 {
3513         Compose *compose = (Compose *)data;
3514         compose_wrap_all(compose);
3515 }
3516
3517 static void compose_wrap_all(Compose *compose)
3518 {
3519         compose_wrap_all_full(compose, FALSE);
3520 }
3521
3522 static void compose_wrap_all_full(Compose *compose, gboolean force)
3523 {
3524         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3525         GtkTextBuffer *buffer;
3526         GtkTextIter iter;
3527
3528         buffer = gtk_text_view_get_buffer(text);
3529
3530         gtk_text_buffer_get_start_iter(buffer, &iter);
3531         while (!gtk_text_iter_is_end(&iter))
3532                 compose_beautify_paragraph(compose, &iter, force);
3533
3534 }
3535
3536 static void compose_set_title(Compose *compose)
3537 {
3538         gchar *str;
3539         gchar *edited;
3540         gchar *subject;
3541         
3542         edited = compose->modified ? _(" [Edited]") : "";
3543         
3544         subject = gtk_editable_get_chars(
3545                         GTK_EDITABLE(compose->subject_entry), 0, -1);
3546
3547         if (subject && strlen(subject))
3548                 str = g_strdup_printf(_("%s - Compose message%s"),
3549                                       subject, edited); 
3550         else
3551                 str = g_strdup_printf(_("[no subject] - Compose message%s"), edited);
3552         gtk_window_set_title(GTK_WINDOW(compose->window), str);
3553         g_free(str);
3554         g_free(subject);
3555 }
3556
3557 /**
3558  * compose_current_mail_account:
3559  * 
3560  * Find a current mail account (the currently selected account, or the
3561  * default account, if a news account is currently selected).  If a
3562  * mail account cannot be found, display an error message.
3563  * 
3564  * Return value: Mail account, or NULL if not found.
3565  **/
3566 static PrefsAccount *
3567 compose_current_mail_account(void)
3568 {
3569         PrefsAccount *ac;
3570
3571         if (cur_account && cur_account->protocol != A_NNTP)
3572                 ac = cur_account;
3573         else {
3574                 ac = account_get_default();
3575                 if (!ac || ac->protocol == A_NNTP) {
3576                         alertpanel_error(_("Account for sending mail is not specified.\n"
3577                                            "Please select a mail account before sending."));
3578                         return NULL;
3579                 }
3580         }
3581         return ac;
3582 }
3583
3584 static void compose_select_account(Compose *compose, PrefsAccount *account,
3585                                    gboolean init)
3586 {
3587         GtkItemFactory *ifactory;
3588
3589         g_return_if_fail(account != NULL);
3590
3591         compose->account = account;
3592
3593         compose_set_title(compose);
3594
3595         ifactory = gtk_item_factory_from_widget(compose->menubar);
3596
3597         if (account->default_sign && compose->mode != COMPOSE_REDIRECT)
3598                 menu_set_active(ifactory, "/Options/Sign", TRUE);
3599         else
3600                 menu_set_active(ifactory, "/Options/Sign", FALSE);
3601         if (account->default_encrypt && compose->mode != COMPOSE_REDIRECT)
3602                 menu_set_active(ifactory, "/Options/Encrypt", TRUE);
3603         else
3604                 menu_set_active(ifactory, "/Options/Encrypt", FALSE);
3605                                        
3606         activate_privacy_system(compose, account, FALSE);
3607
3608         if (!init && compose->mode != COMPOSE_REDIRECT)
3609                 compose_insert_sig(compose, TRUE);
3610 }
3611
3612 gboolean compose_check_for_valid_recipient(Compose *compose) {
3613         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
3614         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
3615         gboolean recipient_found = FALSE;
3616         GSList *list;
3617         gchar **strptr;
3618
3619         /* free to and newsgroup list */
3620         slist_free_strings(compose->to_list);
3621         g_slist_free(compose->to_list);
3622         compose->to_list = NULL;
3623                         
3624         slist_free_strings(compose->newsgroup_list);
3625         g_slist_free(compose->newsgroup_list);
3626         compose->newsgroup_list = NULL;
3627
3628         /* search header entries for to and newsgroup entries */
3629         for (list = compose->header_list; list; list = list->next) {
3630                 gchar *header;
3631                 gchar *entry;
3632                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3633                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3634                 g_strstrip(entry);
3635                 if (entry[0] != '\0') {
3636                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
3637                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3638                                         compose->to_list = address_list_append(compose->to_list, entry);
3639                                         recipient_found = TRUE;
3640                                 }
3641                         }
3642                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
3643                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3644                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
3645                                         recipient_found = TRUE;
3646                                 }
3647                         }
3648                 }
3649                 g_free(header);
3650                 g_free(entry);
3651         }
3652         return recipient_found;
3653 }
3654
3655 static gboolean compose_check_for_set_recipients(Compose *compose)
3656 {
3657         if (compose->account->set_autocc && compose->account->auto_cc) {
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("Cc:") : "Cc:"))) {
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 CC address. Send anyway?"),
3680                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3681                         if (aval != G_ALERTALTERNATE)
3682                                 return FALSE;
3683                 }
3684         }
3685         if (compose->account->set_autobcc && compose->account->auto_bcc) {
3686                 gboolean found_other = FALSE;
3687                 GSList *list;
3688                 /* search header entries for to and newsgroup entries */
3689                 for (list = compose->header_list; list; list = list->next) {
3690                         gchar *entry;
3691                         gchar *header;
3692                         entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3693                         header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3694                         g_strstrip(entry);
3695                         if (strcmp(entry, compose->account->auto_cc)
3696                         ||  strcmp(header, (prefs_common.trans_hdr ? gettext("Bcc:") : "Bcc:"))) {
3697                                 found_other = TRUE;
3698                                 g_free(entry);
3699                                 break;
3700                         }
3701                         g_free(entry);
3702                         g_free(header);
3703                 }
3704                 if (!found_other) {
3705                         AlertValue aval;
3706                         aval = alertpanel(_("Send"),
3707                                           _("The only recipient is the default BCC address. Send anyway?"),
3708                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3709                         if (aval != G_ALERTALTERNATE)
3710                                 return FALSE;
3711                 }
3712         }
3713         return TRUE;
3714 }
3715
3716 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
3717 {
3718         const gchar *str;
3719
3720         if (compose_check_for_valid_recipient(compose) == FALSE) {
3721                 alertpanel_error(_("Recipient is not specified."));
3722                 return FALSE;
3723         }
3724
3725         if (compose_check_for_set_recipients(compose) == FALSE) {
3726                 return FALSE;
3727         }
3728
3729         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3730         if (*str == '\0' && check_subject == TRUE) {
3731                 AlertValue aval;
3732
3733                 aval = alertpanel(_("Send"),
3734                                   _("Subject is empty. Send it anyway?"),
3735                                   GTK_STOCK_CANCEL, _("+_Send"), NULL);
3736                 if (aval != G_ALERTALTERNATE)
3737                         return FALSE;
3738         }
3739
3740         return TRUE;
3741 }
3742
3743 gint compose_send(Compose *compose)
3744 {
3745         gint msgnum;
3746         FolderItem *folder;
3747         gint val = -1;
3748         gchar *msgpath;
3749
3750         compose_allow_user_actions (compose, FALSE);
3751         compose->sending = TRUE;
3752
3753         if (compose_check_entries(compose, TRUE) == FALSE)
3754                 goto bail;
3755
3756         val = compose_queue(compose, &msgnum, &folder);
3757
3758         if (val) {
3759                 if (val == -4) {
3760                         alertpanel_error(_("Could not queue message for sending:\n\n"
3761                                            "Charset conversion failed."));
3762                 } else if (val == -3) {
3763                         alertpanel_error(_("Could not queue message for sending:\n\n"
3764                                            "Signature failed."));
3765                 } else if (val == -2 && errno != 0) {
3766                         alertpanel_error(_("Could not queue message for sending:\n\n%s."), strerror(errno));
3767                 } else {
3768                         alertpanel_error(_("Could not queue message for sending."));
3769                 }
3770                 goto bail;
3771         }
3772
3773
3774         if (prefs_common.send_dialog_mode != SEND_DIALOG_ALWAYS) {
3775                 compose->sending = FALSE;
3776                 compose_close(compose);
3777                 /* No more compose access in the normal codepath 
3778                  * after this point! */
3779                 compose = NULL;
3780         }
3781
3782         if (msgnum == 0) {
3783                 alertpanel_error(_("The message was queued but could not be "
3784                                    "sent.\nUse \"Send queued messages\" from "
3785                                    "the main window to retry."));
3786                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3787                         compose->sending = FALSE;
3788                         compose->modified = TRUE; 
3789                         compose_allow_user_actions (compose, TRUE);
3790                 }
3791                 return 0;
3792         }
3793         
3794         msgpath = folder_item_fetch_msg(folder, msgnum);
3795         val = procmsg_send_message_queue(msgpath);
3796         g_free(msgpath);
3797
3798         if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3799                 compose->sending = FALSE;
3800                 compose_allow_user_actions (compose, TRUE);
3801                 if (val != 0) {
3802                         folder_item_remove_msg(folder, msgnum);
3803                         folder_item_scan(folder);
3804                 }
3805         }
3806
3807         if (val == 0) {
3808                 folder_item_remove_msg(folder, msgnum);
3809                 folder_item_scan(folder);
3810                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS)
3811                         compose_close(compose);
3812         } else {
3813                 alertpanel_error(_("The message was queued but could not be "
3814                                    "sent.\nUse \"Send queued messages\" from "
3815                                    "the main window to retry."));
3816                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3817                         compose_allow_user_actions (compose, TRUE);
3818                         compose->modified = TRUE; 
3819                         compose->sending = FALSE;               
3820                 }
3821                 return -1;
3822         }
3823
3824         return 0;
3825
3826 bail:
3827         compose_allow_user_actions (compose, TRUE);
3828         compose->sending = FALSE;
3829         compose->modified = TRUE; 
3830
3831         return -1;
3832 }
3833
3834 static gboolean compose_use_attach(Compose *compose) 
3835 {
3836         GtkTreeModel *model = gtk_tree_view_get_model
3837                                 (GTK_TREE_VIEW(compose->attach_clist));
3838         return gtk_tree_model_iter_n_children(model, NULL) > 0;
3839 }
3840
3841 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3842                                                            FILE *fp)
3843 {
3844         gchar buf[BUFFSIZE];
3845         gchar *str;
3846         gboolean first_to_address;
3847         gboolean first_cc_address;
3848         GSList *list;
3849         ComposeHeaderEntry *headerentry;
3850         const gchar *headerentryname;
3851         gchar *cc_hdr;
3852         gchar *to_hdr;
3853
3854         debug_print("Writing redirect header\n");
3855
3856         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3857         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3858
3859         first_to_address = TRUE;
3860         for (list = compose->header_list; list; list = list->next) {
3861                 headerentry = ((ComposeHeaderEntry *)list->data);
3862                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3863
3864                 if (g_utf8_collate(headerentryname, to_hdr) == 0) {
3865                         const gchar *entstr = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3866                         Xstrdup_a(str, entstr, return -1);
3867                         g_strstrip(str);
3868                         if (str[0] != '\0') {
3869                                 compose_convert_header
3870                                         (compose, buf, sizeof(buf), str,
3871                                         strlen("Resent-To") + 2, TRUE);
3872
3873                                 if (first_to_address) {
3874                                         fprintf(fp, "Resent-To: ");
3875                                         first_to_address = FALSE;
3876                                 } else {
3877                                         fprintf(fp, ",");
3878                                 }
3879                                 fprintf(fp, "%s", buf);
3880                         }
3881                 }
3882         }
3883         if (!first_to_address) {
3884                 fprintf(fp, "\n");
3885         }
3886
3887         first_cc_address = TRUE;
3888         for (list = compose->header_list; list; list = list->next) {
3889                 headerentry = ((ComposeHeaderEntry *)list->data);
3890                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3891
3892                 if (g_utf8_collate(headerentryname, cc_hdr) == 0) {
3893                         const gchar *strg = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3894                         Xstrdup_a(str, strg, return -1);
3895                         g_strstrip(str);
3896                         if (str[0] != '\0') {
3897                                 compose_convert_header
3898                                         (compose, buf, sizeof(buf), str,
3899                                         strlen("Resent-Cc") + 2, TRUE);
3900
3901                                 if (first_cc_address) {
3902                                         fprintf(fp, "Resent-Cc: ");
3903                                         first_cc_address = FALSE;
3904                                 } else {
3905                                         fprintf(fp, ",");
3906                                 }
3907                                 fprintf(fp, "%s", buf);
3908                         }
3909                 }
3910         }
3911         if (!first_cc_address) {
3912                 fprintf(fp, "\n");
3913         }
3914         
3915         return(0);
3916 }
3917
3918 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3919 {
3920         gchar buf[BUFFSIZE];
3921         gchar *str;
3922         const gchar *entstr;
3923         /* struct utsname utsbuf; */
3924
3925         g_return_val_if_fail(fp != NULL, -1);
3926         g_return_val_if_fail(compose->account != NULL, -1);
3927         g_return_val_if_fail(compose->account->address != NULL, -1);
3928
3929         /* Resent-Date */
3930         get_rfc822_date(buf, sizeof(buf));
3931         fprintf(fp, "Resent-Date: %s\n", buf);
3932
3933         /* Resent-From */
3934         if (compose->account->name && *compose->account->name) {
3935                 compose_convert_header
3936                         (compose, buf, sizeof(buf), compose->account->name,
3937                          strlen("From: "), TRUE);
3938                 fprintf(fp, "Resent-From: %s <%s>\n",
3939                         buf, compose->account->address);
3940         } else
3941                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3942
3943         /* Subject */
3944         entstr = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3945         if (*entstr != '\0') {
3946                 Xstrdup_a(str, entstr, return -1);
3947                 g_strstrip(str);
3948                 if (*str != '\0') {
3949                         compose_convert_header(compose, buf, sizeof(buf), str,
3950                                                strlen("Subject: "), FALSE);
3951                         fprintf(fp, "Subject: %s\n", buf);
3952                 }
3953         }
3954
3955         /* Resent-Message-ID */
3956         if (compose->account->gen_msgid) {
3957                 generate_msgid(buf, sizeof(buf));
3958                 fprintf(fp, "Resent-Message-ID: <%s>\n", buf);
3959                 compose->msgid = g_strdup(buf);
3960         }
3961
3962         compose_redirect_write_headers_from_headerlist(compose, fp);
3963
3964         /* separator between header and body */
3965         fputs("\n", fp);
3966
3967         return 0;
3968 }
3969
3970 static gint compose_redirect_write_to_file(Compose *compose, FILE *fdest)
3971 {
3972         FILE *fp;
3973         size_t len;
3974         gchar buf[BUFFSIZE];
3975
3976         if ((fp = g_fopen(compose->redirect_filename, "rb")) == NULL) {
3977                 FILE_OP_ERROR(compose->redirect_filename, "fopen");
3978                 return -1;
3979         }
3980
3981         while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
3982                 /* should filter returnpath, delivered-to */
3983                 if (g_ascii_strncasecmp(buf, "Return-Path:",
3984                                         strlen("Return-Path:")) == 0 ||
3985                     g_ascii_strncasecmp(buf, "Delivered-To:",
3986                                         strlen("Delivered-To:")) == 0 ||
3987                     g_ascii_strncasecmp(buf, "Received:",
3988                                         strlen("Received:")) == 0 ||
3989                     g_ascii_strncasecmp(buf, "Subject:",
3990                                         strlen("Subject:")) == 0 ||
3991                     g_ascii_strncasecmp(buf, "X-UIDL:",
3992                                         strlen("X-UIDL:")) == 0)
3993                         continue;
3994
3995                 if (fputs(buf, fdest) == -1)
3996                         goto error;
3997
3998                 if (!prefs_common.redirect_keep_from) {
3999                         if (g_ascii_strncasecmp(buf, "From:",
4000                                           strlen("From:")) == 0) {
4001                                 fputs(" (by way of ", fdest);
4002                                 if (compose->account->name
4003                                     && *compose->account->name) {
4004                                         compose_convert_header
4005                                                 (compose, buf, sizeof(buf),
4006                                                  compose->account->name,
4007                                                  strlen("From: "),
4008                                                  FALSE);
4009                                         fprintf(fdest, "%s <%s>",
4010                                                 buf,
4011                                                 compose->account->address);
4012                                 } else
4013                                         fprintf(fdest, "%s",
4014                                                 compose->account->address);
4015                                 fputs(")", fdest);
4016                         }
4017                 }
4018
4019                 if (fputs("\n", fdest) == -1)
4020                         goto error;
4021         }
4022
4023         compose_redirect_write_headers(compose, fdest);
4024
4025         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
4026                 if (fwrite(buf, sizeof(gchar), len, fdest) != len)
4027                         goto error;
4028         }
4029
4030         fclose(fp);
4031
4032         return 0;
4033 error:
4034         fclose(fp);
4035
4036         return -1;
4037 }
4038
4039 static gint compose_write_to_file(Compose *compose, FILE *fp, gint action)
4040 {
4041         GtkTextBuffer *buffer;
4042         GtkTextIter start, end;
4043         gchar *chars;
4044         gchar *buf;
4045         const gchar *out_codeset;
4046         EncodingType encoding;
4047         MimeInfo *mimemsg, *mimetext;
4048         gint line;
4049
4050         /* create message MimeInfo */
4051         mimemsg = procmime_mimeinfo_new();
4052         mimemsg->type = MIMETYPE_MESSAGE;
4053         mimemsg->subtype = g_strdup("rfc822");
4054         mimemsg->content = MIMECONTENT_MEM;
4055         mimemsg->tmp = TRUE; /* must free content later */
4056         mimemsg->data.mem = compose_get_header(compose);
4057
4058         /* Create text part MimeInfo */
4059         /* get all composed text */
4060         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
4061         gtk_text_buffer_get_start_iter(buffer, &start);
4062         gtk_text_buffer_get_end_iter(buffer, &end);
4063         chars = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
4064         if (is_ascii_str(chars)) {
4065                 buf = chars;
4066                 chars = NULL;
4067                 out_codeset = CS_US_ASCII;
4068                 encoding = ENC_7BIT;
4069         } else {
4070                 const gchar *src_codeset = CS_INTERNAL;
4071
4072                 out_codeset = conv_get_charset_str(compose->out_encoding);
4073
4074                 if (!out_codeset) {
4075                         gchar *test_conv_global_out = NULL;
4076                         gchar *test_conv_reply = NULL;
4077
4078                         /* automatic mode. be automatic. */
4079                         codeconv_set_strict(TRUE);
4080                         
4081                         out_codeset = conv_get_outgoing_charset_str();
4082                         if (out_codeset) {
4083                                 debug_print("trying to convert to %s\n", out_codeset);
4084                                 test_conv_global_out = conv_codeset_strdup(chars, src_codeset, out_codeset);
4085                         }
4086                         
4087                         if (!test_conv_global_out && compose->orig_charset) {
4088                                 out_codeset = compose->orig_charset;
4089                                 debug_print("failure; trying to convert to %s\n", out_codeset);
4090                                 test_conv_reply = conv_codeset_strdup(chars, src_codeset, out_codeset);
4091                         }
4092                         
4093                         if (!test_conv_global_out && !test_conv_reply) {
4094                                 /* we're lost */
4095                                 out_codeset = CS_INTERNAL;
4096                                 debug_print("finally using %s\n", out_codeset);
4097                         }
4098                         g_free(test_conv_global_out);
4099                         g_free(test_conv_reply);
4100                         codeconv_set_strict(FALSE);
4101                 }
4102
4103                 if (!g_ascii_strcasecmp(out_codeset, CS_US_ASCII))
4104                         out_codeset = CS_ISO_8859_1;
4105
4106                 if (prefs_common.encoding_method == CTE_BASE64)
4107                         encoding = ENC_BASE64;
4108                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
4109                         encoding = ENC_QUOTED_PRINTABLE;
4110                 else if (prefs_common.encoding_method == CTE_8BIT)
4111                         encoding = ENC_8BIT;
4112                 else
4113                         encoding = procmime_get_encoding_for_charset(out_codeset);
4114
4115                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
4116                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
4117
4118                 if (action == COMPOSE_WRITE_FOR_SEND) {
4119                         codeconv_set_strict(TRUE);
4120                         buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
4121                         codeconv_set_strict(FALSE);
4122
4123                         if (!buf) {
4124                                 AlertValue aval;
4125                                 gchar *msg;
4126
4127                                 msg = g_strdup_printf(_("Can't convert the character encoding of the message \n"
4128                                                         "to the specified %s charset.\n"
4129                                                         "Send it as %s?"), out_codeset, src_codeset);
4130                                 aval = alertpanel_full(_("Error"), msg, GTK_STOCK_CANCEL, _("+_Send"), NULL, FALSE,
4131                                                       NULL, ALERT_ERROR, G_ALERTDEFAULT);
4132                                 g_free(msg);
4133
4134                                 if (aval != G_ALERTALTERNATE) {
4135                                         g_free(chars);
4136                                         return -3;
4137                                 } else {
4138                                         buf = chars;
4139                                         out_codeset = src_codeset;
4140                                         chars = NULL;
4141                                 }
4142                         }
4143                 } else {
4144                         buf = chars;
4145                         out_codeset = src_codeset;
4146                         chars = NULL;
4147                 }
4148         }
4149         g_free(chars);
4150
4151         if (encoding == ENC_8BIT || encoding == ENC_7BIT) {
4152                 if (!strncmp(buf, "From ", sizeof("From ")-1) ||
4153                     strstr(buf, "\nFrom ") != NULL) {
4154                         encoding = ENC_QUOTED_PRINTABLE;
4155                 }
4156         }
4157
4158         mimetext = procmime_mimeinfo_new();
4159         mimetext->content = MIMECONTENT_MEM;
4160         mimetext->tmp = TRUE; /* must free content later */
4161         mimetext->data.mem = buf;
4162         mimetext->type = MIMETYPE_TEXT;
4163         mimetext->subtype = g_strdup("plain");
4164         g_hash_table_insert(mimetext->typeparameters, g_strdup("charset"),
4165                             g_strdup(out_codeset));
4166         /* protect trailing spaces when signing message */
4167         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
4168             privacy_system_can_sign(compose->privacy_system)) {
4169                 encoding = ENC_QUOTED_PRINTABLE;
4170         }
4171         
4172         /* check for line length limit */
4173         if (action == COMPOSE_WRITE_FOR_SEND &&
4174             encoding != ENC_QUOTED_PRINTABLE && encoding != ENC_BASE64 &&
4175             check_line_length(buf, 1000, &line) < 0) {
4176                 AlertValue aval;
4177                 gchar *msg;
4178
4179                 msg = g_strdup_printf
4180                         (_("Line %d exceeds the line length limit (998 bytes).\n"
4181                            "The contents of the message might be broken on the way to the delivery.\n"
4182                            "\n"
4183                            "Send it anyway?"), line + 1);
4184                 aval = alertpanel(_("Warning"), msg, GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL);
4185                 g_free(msg);
4186                 if (aval != G_ALERTALTERNATE) {
4187                         return -1;
4188                 }
4189         }
4190         
4191         if (encoding != ENC_UNKNOWN)
4192                 procmime_encode_content(mimetext, encoding);
4193
4194         /* append attachment parts */
4195         if (compose_use_attach(compose)) {
4196                 MimeInfo *mimempart;
4197                 gchar *boundary = NULL;
4198                 mimempart = procmime_mimeinfo_new();
4199                 mimempart->content = MIMECONTENT_EMPTY;
4200                 mimempart->type = MIMETYPE_MULTIPART;
4201                 mimempart->subtype = g_strdup("mixed");
4202
4203                 do {
4204                         if (boundary)
4205                                 g_free(boundary);
4206                         boundary = generate_mime_boundary(NULL);
4207                 } while (strstr(buf, boundary) != NULL);
4208
4209                 g_hash_table_insert(mimempart->typeparameters, g_strdup("boundary"),
4210                                     boundary);
4211
4212                 mimetext->disposition = DISPOSITIONTYPE_INLINE;
4213
4214                 g_node_append(mimempart->node, mimetext->node);
4215                 g_node_append(mimemsg->node, mimempart->node);
4216
4217                 compose_add_attachments(compose, mimempart);
4218         } else
4219                 g_node_append(mimemsg->node, mimetext->node);
4220
4221         /* sign message if sending */
4222         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
4223             privacy_system_can_sign(compose->privacy_system))
4224                 if (!privacy_sign(compose->privacy_system, mimemsg, compose->account))
4225                         return -2;
4226
4227         procmime_write_mimeinfo(mimemsg, fp);
4228         
4229         procmime_mimeinfo_free_all(mimemsg);
4230
4231         return 0;
4232 }
4233
4234 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
4235 {
4236         GtkTextBuffer *buffer;
4237         GtkTextIter start, end;
4238         FILE *fp;
4239         size_t len;
4240         gchar *chars, *tmp;
4241
4242         if ((fp = g_fopen(file, "wb")) == NULL) {
4243                 FILE_OP_ERROR(file, "fopen");
4244                 return -1;
4245         }
4246
4247         /* chmod for security */
4248         if (change_file_mode_rw(fp, file) < 0) {
4249                 FILE_OP_ERROR(file, "chmod");
4250                 g_warning("can't change file mode\n");
4251         }
4252
4253         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
4254         gtk_text_buffer_get_start_iter(buffer, &start);
4255         gtk_text_buffer_get_end_iter(buffer, &end);
4256         tmp = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
4257
4258         chars = conv_codeset_strdup
4259                 (tmp, CS_INTERNAL, conv_get_locale_charset_str());
4260
4261         g_free(tmp);
4262         if (!chars) return -1;
4263
4264         /* write body */
4265         len = strlen(chars);
4266         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
4267                 FILE_OP_ERROR(file, "fwrite");
4268                 g_free(chars);
4269                 fclose(fp);
4270                 g_unlink(file);
4271                 return -1;
4272         }
4273
4274         g_free(chars);
4275
4276         if (fclose(fp) == EOF) {
4277                 FILE_OP_ERROR(file, "fclose");
4278                 g_unlink(file);
4279                 return -1;
4280         }
4281         return 0;
4282 }
4283
4284 static gint compose_remove_reedit_target(Compose *compose, gboolean force)
4285 {
4286         FolderItem *item;
4287         MsgInfo *msginfo = compose->targetinfo;
4288
4289         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
4290         if (!msginfo) return -1;
4291
4292         if (!force && MSG_IS_LOCKED(msginfo->flags))
4293                 return 0;
4294
4295         item = msginfo->folder;
4296         g_return_val_if_fail(item != NULL, -1);
4297
4298         if (procmsg_msg_exist(msginfo) &&
4299             (folder_has_parent_of_type(item, F_QUEUE) ||
4300              folder_has_parent_of_type(item, F_DRAFT) 
4301              || msginfo == compose->autosaved_draft)) {
4302                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
4303                         g_warning("can't remove the old message\n");
4304                         return -1;
4305                 }
4306         }
4307
4308         return 0;
4309 }
4310
4311 void compose_remove_draft(Compose *compose)
4312 {
4313         FolderItem *drafts;
4314         MsgInfo *msginfo = compose->targetinfo;
4315         drafts = account_get_special_folder(compose->account, F_DRAFT);
4316
4317         if (procmsg_msg_exist(msginfo)) {
4318                 folder_item_remove_msg(drafts, msginfo->msgnum);
4319         }
4320
4321 }
4322
4323 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
4324 {
4325         return compose_queue_sub (compose, msgnum, item, FALSE);
4326 }
4327 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
4328 {
4329         FolderItem *queue;
4330         gchar *tmp;
4331         FILE *fp;
4332         GSList *cur;
4333         gint num;
4334         static gboolean lock = FALSE;
4335         PrefsAccount *mailac = NULL, *newsac = NULL;
4336         
4337         debug_print("queueing message...\n");
4338         g_return_val_if_fail(compose->account != NULL, -1);
4339
4340         lock = TRUE;
4341         
4342         if (compose_check_entries(compose, check_subject) == FALSE) {
4343                 lock = FALSE;
4344                 return -1;
4345         }
4346
4347         if (!compose->to_list && !compose->newsgroup_list) {
4348                 g_warning("can't get recipient list.");
4349                 lock = FALSE;
4350                 return -1;
4351         }
4352
4353         if (compose->to_list) {
4354                 if (compose->account->protocol != A_NNTP)
4355                         mailac = compose->account;
4356                 else if (cur_account && cur_account->protocol != A_NNTP)
4357                         mailac = cur_account;
4358                 else if (!(mailac = compose_current_mail_account())) {
4359                         lock = FALSE;
4360                         alertpanel_error(_("No account for sending mails available!"));
4361                         return -1;
4362                 }
4363         }
4364
4365         if (compose->newsgroup_list) {
4366                 if (compose->account->protocol == A_NNTP)
4367                         newsac = compose->account;
4368                 else if (!newsac->protocol != A_NNTP) {
4369                         lock = FALSE;
4370                         alertpanel_error(_("No account for posting news available!"));
4371                         return -1;
4372                 }                       
4373         }
4374
4375         /* write queue header */
4376         tmp = g_strdup_printf("%s%cqueue.%p", get_tmp_dir(),
4377                               G_DIR_SEPARATOR, compose);
4378         if ((fp = g_fopen(tmp, "wb")) == NULL) {
4379                 FILE_OP_ERROR(tmp, "fopen");
4380                 g_free(tmp);
4381                 return -2;
4382         }
4383
4384         if (change_file_mode_rw(fp, tmp) < 0) {
4385                 FILE_OP_ERROR(tmp, "chmod");
4386                 g_warning("can't change file mode\n");
4387         }
4388
4389         /* queueing variables */
4390         fprintf(fp, "AF:\n");
4391         fprintf(fp, "NF:0\n");
4392         fprintf(fp, "PS:10\n");
4393         fprintf(fp, "SRH:1\n");
4394         fprintf(fp, "SFN:\n");
4395         fprintf(fp, "DSR:\n");
4396         if (compose->msgid)
4397                 fprintf(fp, "MID:<%s>\n", compose->msgid);
4398         else
4399                 fprintf(fp, "MID:\n");
4400         fprintf(fp, "CFG:\n");
4401         fprintf(fp, "PT:0\n");
4402         fprintf(fp, "S:%s\n", compose->account->address);
4403         fprintf(fp, "RQ:\n");
4404         if (mailac)
4405                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
4406         else
4407                 fprintf(fp, "SSV:\n");
4408         if (newsac)
4409                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
4410         else
4411                 fprintf(fp, "NSV:\n");
4412         fprintf(fp, "SSH:\n");
4413         /* write recepient list */
4414         if (compose->to_list) {
4415                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
4416                 for (cur = compose->to_list->next; cur != NULL;
4417                      cur = cur->next)
4418                         fprintf(fp, ",<%s>", (gchar *)cur->data);
4419                 fprintf(fp, "\n");
4420         }
4421         /* write newsgroup list */
4422         if (compose->newsgroup_list) {
4423                 fprintf(fp, "NG:");
4424                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
4425                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
4426                         fprintf(fp, ",%s", (gchar *)cur->data);
4427                 fprintf(fp, "\n");
4428         }
4429         /* Sylpheed account IDs */
4430         if (mailac)
4431                 fprintf(fp, "MAID:%d\n", mailac->account_id);
4432         if (newsac)
4433                 fprintf(fp, "NAID:%d\n", newsac->account_id);
4434
4435         if (compose->privacy_system != NULL) {
4436                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
4437                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
4438                 if (compose->use_encryption) {
4439                         gchar *encdata;
4440
4441                         encdata = privacy_get_encrypt_data(compose->privacy_system, compose->to_list);
4442                         if (encdata != NULL) {
4443                                 if (strcmp(encdata, "_DONT_ENCRYPT_")) {
4444                                         fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
4445                                         fprintf(fp, "X-Sylpheed-Encrypt-Data:%s\n", 
4446                                                 encdata);
4447                                 } /* else we finally dont want to encrypt */
4448                         } else {
4449                                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
4450                                 /* and if encdata was null, it means there's been a problem in 
4451                                  * key selection */
4452                         }
4453                         g_free(encdata);
4454                 }
4455         }
4456
4457         /* Save copy folder */
4458         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
4459                 gchar *savefolderid;
4460                 
4461                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
4462                 fprintf(fp, "SCF:%s\n", savefolderid);
4463                 g_free(savefolderid);
4464         }
4465         /* Save copy folder */
4466         if (compose->return_receipt) {
4467                 fprintf(fp, "RRCPT:1\n");
4468         }
4469         /* Message-ID of message replying to */
4470         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
4471                 gchar *folderid;
4472                 
4473                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
4474                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
4475                 g_free(folderid);
4476         }
4477         /* Message-ID of message forwarding to */
4478         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
4479                 gchar *folderid;
4480                 
4481                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
4482                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
4483                 g_free(folderid);
4484         }
4485         fprintf(fp, "\n");
4486
4487         if (compose->redirect_filename != NULL) {
4488                 if (compose_redirect_write_to_file(compose, fp) < 0) {
4489                         lock = FALSE;
4490                         fclose(fp);
4491                         g_unlink(tmp);
4492                         g_free(tmp);
4493                         return -2;
4494                 }
4495         } else {
4496                 gint result = 0;
4497                 if ((result = compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_SEND)) < 0) {
4498                         lock = FALSE;
4499                         fclose(fp);
4500                         g_unlink(tmp);
4501                         g_free(tmp);
4502                         return result - 1; /* -2 for a generic error, -3 for signing error, -4 for encoding */
4503                 }
4504         }
4505
4506         if (fclose(fp) == EOF) {
4507                 FILE_OP_ERROR(tmp, "fclose");
4508                 g_unlink(tmp);
4509                 g_free(tmp);
4510                 return -2;
4511         }
4512
4513         queue = account_get_special_folder(compose->account, F_QUEUE);
4514         if (!queue) {
4515                 g_warning("can't find queue folder\n");
4516                 g_unlink(tmp);
4517                 g_free(tmp);
4518                 return -1;
4519         }
4520         folder_item_scan(queue);
4521         if ((num = folder_item_add_msg(queue, tmp, NULL, TRUE)) < 0) {
4522                 g_warning("can't queue the message\n");
4523                 g_unlink(tmp);
4524                 g_free(tmp);
4525                 return -1;
4526         }
4527         g_unlink(tmp);
4528         g_free(tmp);
4529
4530         if (compose->mode == COMPOSE_REEDIT) {
4531                 compose_remove_reedit_target(compose, FALSE);
4532         }
4533
4534         if ((msgnum != NULL) && (item != NULL)) {
4535                 *msgnum = num;
4536                 *item = queue;
4537         }
4538
4539         return 0;
4540 }
4541
4542 static void compose_add_attachments(Compose *compose, MimeInfo *parent)
4543 {
4544         AttachInfo *ainfo;
4545         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
4546         MimeInfo *mimepart;
4547         struct stat statbuf;
4548         gchar *type, *subtype;
4549         GtkTreeModel *model;
4550         GtkTreeIter iter;
4551
4552         model = gtk_tree_view_get_model(tree_view);
4553         
4554         if (!gtk_tree_model_get_iter_first(model, &iter))
4555                 return;
4556         do {
4557                 gtk_tree_model_get(model, &iter,
4558                                    COL_DATA, &ainfo,
4559                                    -1);
4560                                                            
4561                 mimepart = procmime_mimeinfo_new();
4562                 mimepart->content = MIMECONTENT_FILE;
4563                 mimepart->data.filename = g_strdup(ainfo->file);
4564                 mimepart->tmp = FALSE; /* or we destroy our attachment */
4565                 mimepart->offset = 0;
4566
4567                 stat(ainfo->file, &statbuf);
4568                 mimepart->length = statbuf.st_size;
4569
4570                 type = g_strdup(ainfo->content_type);
4571
4572                 if (!strchr(type, '/')) {
4573                         g_free(type);
4574                         type = g_strdup("application/octet-stream");
4575                 }
4576
4577                 subtype = strchr(type, '/') + 1;
4578                 *(subtype - 1) = '\0';
4579                 mimepart->type = procmime_get_media_type(type);
4580                 mimepart->subtype = g_strdup(subtype);
4581                 g_free(type);
4582
4583                 if (mimepart->type == MIMETYPE_MESSAGE && 
4584                     !g_ascii_strcasecmp(mimepart->subtype, "rfc822")) {
4585                         mimepart->disposition = DISPOSITIONTYPE_INLINE;
4586                 } else {
4587                         g_hash_table_insert(mimepart->typeparameters,
4588                                             g_strdup("name"), g_strdup(ainfo->name));
4589                         g_hash_table_insert(mimepart->dispositionparameters,
4590                                             g_strdup("filename"), g_strdup(ainfo->name));
4591                         mimepart->disposition = DISPOSITIONTYPE_ATTACHMENT;
4592                 }
4593
4594                 if (compose->use_signing) {
4595                         if (ainfo->encoding == ENC_7BIT)
4596                                 ainfo->encoding = ENC_QUOTED_PRINTABLE;
4597                         else if (ainfo->encoding == ENC_8BIT)
4598                                 ainfo->encoding = ENC_BASE64;
4599                 }
4600                 
4601                 procmime_encode_content(mimepart, ainfo->encoding);
4602
4603                 g_node_append(parent->node, mimepart->node);
4604         } while (gtk_tree_model_iter_next(model, &iter));
4605 }
4606
4607 #define QUOTE_IF_REQUIRED(out, str)                                     \
4608 {                                                                       \
4609         if (*str != '"' && strpbrk(str, ",.[]<>")) {                    \
4610                 gchar *__tmp;                                           \
4611                 gint len;                                               \
4612                                                                         \
4613                 len = strlen(str) + 3;                                  \
4614                 if ((__tmp = alloca(len)) == NULL) {                    \
4615                         g_warning("can't allocate memory\n");           \
4616                         g_string_free(header, TRUE);                    \
4617                         return NULL;                                    \
4618                 }                                                       \
4619                 g_snprintf(__tmp, len, "\"%s\"", str);                  \
4620                 out = __tmp;                                            \
4621         } else {                                                        \
4622                 gchar *__tmp;                                           \
4623                                                                         \
4624                 if ((__tmp = alloca(strlen(str) + 1)) == NULL) {        \
4625                         g_warning("can't allocate memory\n");           \
4626                         g_string_free(header, TRUE);                    \
4627                         return NULL;                                    \
4628                 } else                                                  \
4629                         strcpy(__tmp, str);                             \
4630                                                                         \
4631                 out = __tmp;                                            \
4632         }                                                               \
4633 }
4634
4635 #define IS_IN_CUSTOM_HEADER(header) \
4636         (compose->account->add_customhdr && \
4637          custom_header_find(compose->account->customhdr_list, header) != NULL)
4638
4639 static void compose_add_headerfield_from_headerlist(Compose *compose, 
4640                                                     GString *header, 
4641                                                     const gchar *fieldname,
4642                                                     const gchar *seperator)
4643 {
4644         gchar *str, *fieldname_w_colon, *trans_fieldname;
4645         gboolean add_field = FALSE;
4646         GSList *list;
4647         ComposeHeaderEntry *headerentry;
4648         const gchar * headerentryname;
4649         GString *fieldstr;
4650
4651         if (IS_IN_CUSTOM_HEADER(fieldname))
4652                 return;
4653
4654         debug_print("Adding %s-fields\n", fieldname);
4655
4656         fieldstr = g_string_sized_new(64);
4657
4658         fieldname_w_colon = g_strconcat(fieldname, ":", NULL);
4659         trans_fieldname = (prefs_common.trans_hdr ? gettext(fieldname_w_colon) : fieldname_w_colon);
4660
4661         for (list = compose->header_list; list; list = list->next) {
4662                 headerentry = ((ComposeHeaderEntry *)list->data);
4663                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
4664
4665                 if (!g_utf8_collate(trans_fieldname, headerentryname)) {
4666                         str = gtk_editable_get_chars(GTK_EDITABLE(headerentry->entry), 0, -1);
4667                         g_strstrip(str);
4668                         if (str[0] != '\0') {
4669                                 if (add_field)
4670                                         g_string_append(fieldstr, seperator);
4671                                 g_string_append(fieldstr, str);
4672                                 add_field = TRUE;
4673                         }
4674                         g_free(str);
4675                 }
4676         }
4677         if (add_field) {
4678                 gchar *buf;
4679
4680                 buf = g_new0(gchar, fieldstr->len * 4 + 256);
4681                 compose_convert_header
4682                         (compose, buf, fieldstr->len * 4  + 256, fieldstr->str,
4683                         strlen(fieldname) + 2, TRUE);
4684                 g_string_append_printf(header, "%s: %s\n", fieldname, buf);
4685                 g_free(buf);
4686         }
4687
4688         g_free(fieldname_w_colon);
4689         g_string_free(fieldstr, TRUE);
4690
4691         return;
4692 }
4693
4694 static gchar *compose_get_header(Compose *compose)
4695 {
4696         gchar buf[BUFFSIZE];
4697         const gchar *entry_str;
4698         gchar *str;
4699         gchar *name;
4700         GSList *list;
4701         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4702         GString *header;
4703
4704         g_return_val_if_fail(compose->account != NULL, NULL);
4705         g_return_val_if_fail(compose->account->address != NULL, NULL);
4706
4707         header = g_string_sized_new(64);
4708
4709         /* Date */
4710         if (compose->account->add_date) {
4711                 get_rfc822_date(buf, sizeof(buf));
4712                 g_string_append_printf(header, "Date: %s\n", buf);
4713         }
4714
4715         /* From */
4716         if (compose->account->name && *compose->account->name) {
4717                 compose_convert_header
4718                         (compose, buf, sizeof(buf), compose->account->name,
4719                          strlen("From: "), TRUE);
4720                 QUOTE_IF_REQUIRED(name, buf);
4721                 g_string_append_printf(header, "From: %s <%s>\n",
4722                         name, compose->account->address);
4723         } else
4724                 g_string_append_printf(header, "From: %s\n", compose->account->address);
4725         
4726         /* To */
4727         compose_add_headerfield_from_headerlist(compose, header, "To", ", ");
4728
4729         /* Newsgroups */
4730         compose_add_headerfield_from_headerlist(compose, header, "Newsgroups", ",");
4731
4732         /* Cc */
4733         compose_add_headerfield_from_headerlist(compose, header, "Cc", ", ");
4734
4735         /* Bcc */
4736         compose_add_headerfield_from_headerlist(compose, header, "Bcc", ", ");
4737
4738         /* Subject */
4739         str = gtk_editable_get_chars(GTK_EDITABLE(compose->subject_entry), 0, -1);
4740
4741         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
4742                 g_strstrip(str);
4743                 if (*str != '\0') {
4744                         compose_convert_header(compose, buf, sizeof(buf), str,
4745                                                strlen("Subject: "), FALSE);
4746                         g_string_append_printf(header, "Subject: %s\n", buf);
4747                 }
4748         }
4749         g_free(str);
4750
4751         /* Message-ID */
4752         if (compose->account->gen_msgid) {
4753                 generate_msgid(buf, sizeof(buf));
4754                 g_string_append_printf(header, "Message-ID: <%s>\n", buf);
4755                 compose->msgid = g_strdup(buf);
4756         }
4757
4758         if (compose->remove_references == FALSE) {
4759                 /* In-Reply-To */
4760                 if (compose->inreplyto && compose->to_list)
4761                         g_string_append_printf(header, "In-Reply-To: <%s>\n", compose->inreplyto);
4762         
4763                 /* References */
4764                 if (compose->references)
4765                         g_string_append_printf(header, "References: %s\n", compose->references);
4766         }
4767
4768         /* Followup-To */
4769         compose_add_headerfield_from_headerlist(compose, header, "Followup-To", ",");
4770
4771         /* Reply-To */
4772         compose_add_headerfield_from_headerlist(compose, header, "Reply-To", ", ");
4773
4774         /* Organization */
4775         if (compose->account->organization &&
4776             strlen(compose->account->organization) &&
4777             !IS_IN_CUSTOM_HEADER("Organization")) {
4778                 compose_convert_header(compose, buf, sizeof(buf),
4779                                        compose->account->organization,
4780                                        strlen("Organization: "), FALSE);
4781                 g_string_append_printf(header, "Organization: %s\n", buf);
4782         }
4783
4784         /* Program version and system info */
4785         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer") &&
4786             !compose->newsgroup_list) {
4787                 g_string_append_printf(header, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
4788                         prog_version,
4789                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4790                         TARGET_ALIAS);
4791         }
4792         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4793                 g_string_append_printf(header, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4794                         prog_version,
4795                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4796                         TARGET_ALIAS);
4797         }
4798
4799         /* custom headers */
4800         if (compose->account->add_customhdr) {
4801                 GSList *cur;
4802
4803                 for (cur = compose->account->customhdr_list; cur != NULL;
4804                      cur = cur->next) {
4805                         CustomHeader *chdr = (CustomHeader *)cur->data;
4806
4807                         if (custom_header_is_allowed(chdr->name)) {
4808                                 compose_convert_header
4809                                         (compose, buf, sizeof(buf),
4810                                          chdr->value ? chdr->value : "",
4811                                          strlen(chdr->name) + 2, FALSE);
4812                                 g_string_append_printf(header, "%s: %s\n", chdr->name, buf);
4813                         }
4814                 }
4815         }
4816
4817         /* PRIORITY */
4818         switch (compose->priority) {
4819                 case PRIORITY_HIGHEST: g_string_append_printf(header, "Importance: high\n"
4820                                                    "X-Priority: 1 (Highest)\n");
4821                         break;
4822                 case PRIORITY_HIGH: g_string_append_printf(header, "Importance: high\n"
4823                                                 "X-Priority: 2 (High)\n");
4824                         break;
4825                 case PRIORITY_NORMAL: break;
4826                 case PRIORITY_LOW: g_string_append_printf(header, "Importance: low\n"
4827                                                "X-Priority: 4 (Low)\n");
4828                         break;
4829                 case PRIORITY_LOWEST: g_string_append_printf(header, "Importance: low\n"
4830                                                   "X-Priority: 5 (Lowest)\n");
4831                         break;
4832                 default: debug_print("compose: priority unknown : %d\n",
4833                                      compose->priority);
4834         }
4835
4836         /* Request Return Receipt */
4837         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4838                 if (compose->return_receipt) {
4839                         if (compose->account->name
4840                             && *compose->account->name) {
4841                                 compose_convert_header(compose, buf, sizeof(buf), 
4842                                                        compose->account->name, 
4843                                                        strlen("Disposition-Notification-To: "),
4844                                                        TRUE);
4845                                 g_string_append_printf(header, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4846                         } else
4847                                 g_string_append_printf(header, "Disposition-Notification-To: %s\n", compose->account->address);
4848                 }
4849         }
4850
4851         /* get special headers */
4852         for (list = compose->header_list; list; list = list->next) {
4853                 ComposeHeaderEntry *headerentry;
4854                 gchar *tmp;
4855                 gchar *headername;
4856                 gchar *headername_wcolon;
4857                 gchar *headername_trans;
4858                 gchar *headervalue;
4859                 gchar **string;
4860                 gboolean standard_header = FALSE;
4861
4862                 headerentry = ((ComposeHeaderEntry *)list->data);
4863                 
4864                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4865                 if (strchr(tmp, ' ') != NULL || strchr(tmp, '\r') != NULL || strchr(tmp, '\n') != NULL) {
4866                         g_free(tmp);
4867                         continue;
4868                 }
4869
4870                 if (!strstr(tmp, ":")) {
4871                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4872                         headername = g_strdup(tmp);
4873                 } else {
4874                         headername_wcolon = g_strdup(tmp);
4875                         headername = g_strdup(strtok(tmp, ":"));
4876                 }
4877                 g_free(tmp);
4878                 
4879                 entry_str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4880                 Xstrdup_a(headervalue, entry_str, return NULL);
4881                 subst_char(headervalue, '\r', ' ');
4882                 subst_char(headervalue, '\n', ' ');
4883                 string = std_headers;
4884                 while (*string != NULL) {
4885                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4886                         if (!strcmp(headername_trans,headername_wcolon))
4887                                 standard_header = TRUE;
4888                         string++;
4889                 }
4890                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4891                         g_string_append_printf(header, "%s %s\n", headername_wcolon, headervalue);
4892                                 
4893                 g_free(headername);
4894                 g_free(headername_wcolon);              
4895         }
4896
4897         str = header->str;
4898         g_string_free(header, FALSE);
4899
4900         return str;
4901 }
4902
4903 #undef IS_IN_CUSTOM_HEADER
4904
4905 static void compose_convert_header(Compose *compose, gchar *dest, gint len, gchar *src,
4906                                    gint header_len, gboolean addr_field)
4907 {
4908         gchar *tmpstr = NULL;
4909         const gchar *out_codeset = NULL;
4910
4911         g_return_if_fail(src != NULL);
4912         g_return_if_fail(dest != NULL);
4913
4914         if (len < 1) return;
4915
4916         tmpstr = g_strdup(src);
4917
4918         subst_char(tmpstr, '\n', ' ');
4919         subst_char(tmpstr, '\r', ' ');
4920         g_strchomp(tmpstr);
4921
4922         if (!g_utf8_validate(tmpstr, -1, NULL)) {
4923                 gchar *mybuf = g_malloc(strlen(tmpstr)*2 +1);
4924                 conv_localetodisp(mybuf, strlen(tmpstr)*2 +1, tmpstr);
4925                 g_free(tmpstr);
4926                 tmpstr = mybuf;
4927         }
4928
4929         codeconv_set_strict(TRUE);
4930         conv_encode_header_full(dest, len, tmpstr, header_len, addr_field, 
4931                 conv_get_charset_str(compose->out_encoding));
4932         codeconv_set_strict(FALSE);
4933         
4934         if (!dest || *dest == '\0') {
4935                 gchar *test_conv_global_out = NULL;
4936                 gchar *test_conv_reply = NULL;
4937
4938                 /* automatic mode. be automatic. */
4939                 codeconv_set_strict(TRUE);
4940
4941                 out_codeset = conv_get_outgoing_charset_str();
4942                 if (out_codeset) {
4943                         debug_print("trying to convert to %s\n", out_codeset);
4944                         test_conv_global_out = conv_codeset_strdup(src, CS_INTERNAL, out_codeset);
4945                 }
4946
4947                 if (!test_conv_global_out && compose->orig_charset) {
4948                         out_codeset = compose->orig_charset;
4949                         debug_print("failure; trying to convert to %s\n", out_codeset);
4950                         test_conv_reply = conv_codeset_strdup(src, CS_INTERNAL, out_codeset);
4951                 }
4952
4953                 if (!test_conv_global_out && !test_conv_reply) {
4954                         /* we're lost */
4955                         out_codeset = CS_INTERNAL;
4956                         debug_print("finally using %s\n", out_codeset);
4957                 }
4958                 g_free(test_conv_global_out);
4959                 g_free(test_conv_reply);
4960                 conv_encode_header_full(dest, len, tmpstr, header_len, addr_field, 
4961                                         out_codeset);
4962                 codeconv_set_strict(FALSE);
4963         }
4964         g_free(tmpstr);
4965 }
4966
4967 static void compose_create_header_entry(Compose *compose) 
4968 {
4969         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4970
4971         GtkWidget *combo;
4972         GtkWidget *entry;
4973         GList *combo_list = NULL;
4974         gchar **string;
4975         const gchar *header = NULL;
4976         ComposeHeaderEntry *headerentry;
4977         gboolean standard_header = FALSE;
4978
4979         headerentry = g_new0(ComposeHeaderEntry, 1);
4980
4981         /* Combo box */
4982         combo = gtk_combo_new();
4983         string = headers; 
4984         while(*string != NULL) {
4985                 combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
4986                 string++;
4987         }
4988         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
4989         g_list_free(combo_list);
4990         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
4991         g_signal_connect(G_OBJECT(GTK_COMBO(combo)->entry), "grab_focus",
4992                          G_CALLBACK(compose_grab_focus_cb), compose);
4993         gtk_widget_show(combo);
4994         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
4995         if (compose->header_last) {     
4996                 const gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4997                 string = headers;
4998                 while (*string != NULL) {
4999                         if (!strcmp(*string, last_header_entry))
5000                                 standard_header = TRUE;
5001                         string++;
5002                 }
5003                 if (standard_header)
5004                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
5005         }
5006         if (!compose->header_last || !standard_header) {
5007                 switch(compose->account->protocol) {
5008                         case A_NNTP:
5009                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
5010                                 break;
5011                         default:
5012                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
5013                                 break;
5014                 }                                                                   
5015         }
5016         if (header)
5017                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
5018
5019         g_signal_connect_after(G_OBJECT(GTK_COMBO(combo)->entry), "grab_focus",
5020                          G_CALLBACK(compose_grab_focus_cb), compose);
5021
5022         /* Entry field */
5023         entry = gtk_entry_new(); 
5024         gtk_widget_show(entry);
5025         gtk_table_attach(GTK_TABLE(compose->header_table), entry, 1, 2, compose->header_nextrow, compose->header_nextrow+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
5026
5027         g_signal_connect(G_OBJECT(entry), "key-press-event", 
5028                          G_CALLBACK(compose_headerentry_key_press_event_cb), 
5029                          headerentry);
5030         g_signal_connect(G_OBJECT(entry), "changed", 
5031                          G_CALLBACK(compose_headerentry_changed_cb), 
5032                          headerentry);
5033         g_signal_connect_after(G_OBJECT(entry), "grab_focus",
5034                          G_CALLBACK(compose_grab_focus_cb), compose);
5035                          
5036         /* email dnd */
5037         gtk_drag_dest_set(entry, GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5038                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5039                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5040         g_signal_connect(G_OBJECT(entry), "drag_data_received",
5041                          G_CALLBACK(compose_header_drag_received_cb),
5042                          entry);
5043         g_signal_connect(G_OBJECT(entry), "drag-drop",
5044                          G_CALLBACK(compose_drag_drop),
5045                          compose);
5046         
5047         address_completion_register_entry(GTK_ENTRY(entry));
5048
5049         headerentry->compose = compose;
5050         headerentry->combo = combo;
5051         headerentry->entry = entry;
5052         headerentry->headernum = compose->header_nextrow;
5053
5054         compose->header_nextrow++;
5055         compose->header_last = headerentry;
5056 }
5057
5058 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
5059 {
5060         ComposeHeaderEntry *last_header;
5061         
5062         last_header = compose->header_last;
5063         
5064         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
5065         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
5066 }
5067
5068 static GtkWidget *compose_create_header(Compose *compose) 
5069 {
5070         GtkWidget *label;
5071         GtkWidget *hbox;
5072         GtkWidget *from_optmenu_hbox;
5073         GtkWidget *header_scrolledwin;
5074         GtkWidget *header_table;
5075
5076         gint count = 0;
5077
5078         /* header labels and entries */
5079         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
5080         gtk_widget_show(header_scrolledwin);
5081         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
5082
5083         header_table = gtk_table_new(2, 2, FALSE);
5084         gtk_widget_show(header_table);
5085         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
5086         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
5087         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
5088         count = 0;
5089
5090         /* option menu for selecting accounts */
5091         hbox = gtk_hbox_new(FALSE, 0);
5092         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
5093         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
5094         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
5095                          GTK_FILL, 0, 2, 0);
5096         from_optmenu_hbox = compose_account_option_menu_create(compose);
5097         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
5098                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
5099         count++;
5100
5101         compose->header_table = header_table;
5102         compose->header_list = NULL;
5103         compose->header_nextrow = count;
5104
5105         compose_create_header_entry(compose);
5106
5107         compose->table            = NULL;
5108
5109         return header_scrolledwin ;
5110 }
5111
5112 GtkWidget *compose_create_attach(Compose *compose)
5113 {
5114         GtkWidget *attach_scrwin;
5115         GtkWidget *attach_clist;
5116
5117         GtkListStore *store;
5118         GtkCellRenderer *renderer;
5119         GtkTreeViewColumn *column;
5120         GtkTreeSelection *selection;
5121
5122         /* attachment list */
5123         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
5124         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
5125                                        GTK_POLICY_AUTOMATIC,
5126                                        GTK_POLICY_AUTOMATIC);
5127         gtk_widget_set_size_request(attach_scrwin, -1, 80);
5128
5129         store = gtk_list_store_new(N_ATTACH_COLS, 
5130                                    G_TYPE_STRING,
5131                                    G_TYPE_STRING,
5132                                    G_TYPE_STRING,
5133                                    G_TYPE_POINTER,
5134                                    G_TYPE_AUTO_POINTER,
5135                                    -1);
5136         attach_clist = GTK_WIDGET(gtk_tree_view_new_with_model
5137                                         (GTK_TREE_MODEL(store)));
5138         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
5139         g_object_unref(store);
5140         
5141         renderer = gtk_cell_renderer_text_new();
5142         column = gtk_tree_view_column_new_with_attributes
5143                         (_("Mime type"), renderer, "text", 
5144                          COL_MIMETYPE, NULL);
5145         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);                        
5146         
5147         renderer = gtk_cell_renderer_text_new();
5148         column = gtk_tree_view_column_new_with_attributes
5149                         (_("Size"), renderer, "text", 
5150                          COL_SIZE, NULL);
5151         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);                        
5152         
5153         renderer = gtk_cell_renderer_text_new();
5154         column = gtk_tree_view_column_new_with_attributes
5155                         (_("Name"), renderer, "text", 
5156                          COL_NAME, NULL);
5157         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);
5158
5159         gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(attach_clist),
5160                                      prefs_common.enable_rules_hint);
5161         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(attach_clist));
5162         gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE);
5163
5164         g_signal_connect(G_OBJECT(attach_clist), "row_activated",
5165                          G_CALLBACK(attach_selected), compose);
5166         g_signal_connect(G_OBJECT(attach_clist), "button_press_event",
5167                          G_CALLBACK(attach_button_pressed), compose);
5168         g_signal_connect(G_OBJECT(attach_clist), "key_press_event",
5169                          G_CALLBACK(attach_key_pressed), compose);
5170
5171         /* drag and drop */
5172         gtk_drag_dest_set(attach_clist,
5173                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5174                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5175                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5176         g_signal_connect(G_OBJECT(attach_clist), "drag_data_received",
5177                          G_CALLBACK(compose_attach_drag_received_cb),
5178                          compose);
5179         g_signal_connect(G_OBJECT(attach_clist), "drag-drop",
5180                          G_CALLBACK(compose_drag_drop),
5181                          compose);
5182
5183         compose->attach_scrwin = attach_scrwin;
5184         compose->attach_clist  = attach_clist;
5185
5186         return attach_scrwin;
5187 }
5188
5189 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
5190 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
5191
5192 static GtkWidget *compose_create_others(Compose *compose)
5193 {
5194         GtkWidget *table;
5195         GtkWidget *savemsg_checkbtn;
5196         GtkWidget *savemsg_entry;
5197         GtkWidget *savemsg_select;
5198         
5199         guint rowcount = 0;
5200         gchar *folderidentifier;
5201
5202         /* Table for settings */
5203         table = gtk_table_new(3, 1, FALSE);
5204         gtk_widget_show(table);
5205         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
5206         rowcount = 0;
5207
5208         /* Save Message to folder */
5209         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
5210         gtk_widget_show(savemsg_checkbtn);
5211         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
5212         if (account_get_special_folder(compose->account, F_OUTBOX)) {
5213                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
5214         }
5215         g_signal_connect(G_OBJECT(savemsg_checkbtn), "toggled",
5216                          G_CALLBACK(compose_savemsg_checkbtn_cb), compose);
5217
5218         savemsg_entry = gtk_entry_new();
5219         gtk_widget_show(savemsg_entry);
5220         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
5221         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
5222         g_signal_connect_after(G_OBJECT(savemsg_entry), "grab_focus",
5223                          G_CALLBACK(compose_grab_focus_cb), compose);
5224         if (account_get_special_folder(compose->account, F_OUTBOX)) {
5225                 folderidentifier = folder_item_get_identifier(account_get_special_folder
5226                                   (compose->account, F_OUTBOX));
5227                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
5228                 g_free(folderidentifier);
5229         }
5230
5231         savemsg_select = gtkut_get_browse_file_btn(_("_Browse"));
5232         gtk_widget_show(savemsg_select);
5233         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
5234         g_signal_connect(G_OBJECT(savemsg_select), "clicked",
5235                          G_CALLBACK(compose_savemsg_select_cb),
5236                          compose);
5237
5238         rowcount++;
5239
5240         compose->savemsg_checkbtn = savemsg_checkbtn;
5241         compose->savemsg_entry = savemsg_entry;
5242
5243         return table;   
5244 }
5245
5246 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
5247 {
5248         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
5249                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
5250 }
5251
5252 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
5253 {
5254         FolderItem *dest;
5255         gchar * path;
5256
5257         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
5258         if (!dest) return;
5259
5260         path = folder_item_get_identifier(dest);
5261
5262         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
5263         g_free(path);
5264 }
5265
5266 static void entry_paste_clipboard(Compose *compose, GtkWidget *entry, gboolean wrap,
5267                                   GdkAtom clip);
5268
5269 #define BLOCK_WRAP() {                                                  \
5270         prev_autowrap = compose->autowrap;                              \
5271         buffer = gtk_text_view_get_buffer(                              \
5272                                         GTK_TEXT_VIEW(compose->text));  \
5273         compose->autowrap = FALSE;                                      \
5274                                                                         \
5275         g_signal_handlers_block_by_func(G_OBJECT(buffer),               \
5276                                 G_CALLBACK(compose_changed_cb),         \
5277                                 compose);                               \
5278         g_signal_handlers_block_by_func(G_OBJECT(buffer),               \
5279                                 G_CALLBACK(text_inserted),              \
5280                                 compose);                               \
5281 }
5282 #define UNBLOCK_WRAP() {                                                \
5283         compose->autowrap = prev_autowrap;                              \
5284         if (compose->autowrap)                                          \
5285                 compose_wrap_all(compose);                              \
5286                                                                         \
5287         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),             \
5288                                 G_CALLBACK(compose_changed_cb),         \
5289                                 compose);                               \
5290         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),             \
5291                                 G_CALLBACK(text_inserted),              \
5292                                 compose);                               \
5293 }
5294
5295
5296 static gboolean text_clicked(GtkWidget *text, GdkEventButton *event,
5297                                        Compose *compose)
5298 {
5299         gint prev_autowrap;
5300         GtkTextBuffer *buffer;
5301 #if USE_ASPELL
5302         if (event->button == 3) {
5303                 GtkTextIter iter;
5304                 gint x, y;
5305                 /* move the cursor to allow GtkAspell to check the word
5306                  * under the mouse */
5307                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(text),
5308                         GTK_TEXT_WINDOW_TEXT, event->x, event->y,
5309                         &x, &y);
5310                 gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW(text),
5311                         &iter, x, y);
5312                 gtk_text_buffer_place_cursor (GTK_TEXT_VIEW(text)->buffer, &iter);
5313                 return FALSE; /* pass the event so that the right-click goes through */
5314         }
5315 #endif
5316         if (event->button == 2) {
5317                 BLOCK_WRAP();
5318                 entry_paste_clipboard(compose, compose->focused_editable, 
5319                                 prefs_common.linewrap_pastes,
5320                                 GDK_SELECTION_PRIMARY);
5321                 UNBLOCK_WRAP();
5322                 return TRUE;
5323         }
5324         return FALSE;
5325 }
5326
5327 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
5328 {
5329         Compose   *compose;
5330         GtkWidget *window;
5331         GtkWidget *vbox;
5332         GtkWidget *menubar;
5333         GtkWidget *handlebox;
5334
5335         GtkWidget *notebook;
5336
5337         GtkWidget *vbox2;
5338
5339         GtkWidget *label;
5340         GtkWidget *subject_hbox;
5341         GtkWidget *subject_frame;
5342         GtkWidget *subject_entry;
5343         GtkWidget *subject;
5344         GtkWidget *paned;
5345
5346         GtkWidget *edit_vbox;
5347         GtkWidget *ruler_hbox;
5348         GtkWidget *ruler;
5349         GtkWidget *scrolledwin;
5350         GtkWidget *text;
5351         GtkTextBuffer *buffer;
5352         GtkClipboard *clipboard;
5353
5354         UndoMain *undostruct;
5355
5356         gchar *titles[N_ATTACH_COLS];
5357         guint n_menu_entries;
5358         GdkColormap *cmap;
5359         GdkColor color[1];
5360         gboolean success[1];
5361         GtkWidget *popupmenu;
5362         GtkItemFactory *popupfactory;
5363         GtkItemFactory *ifactory;
5364         GtkWidget *tmpl_menu;
5365         gint n_entries;
5366         GtkWidget *menuitem;
5367
5368 #if USE_ASPELL
5369         GtkAspell * gtkaspell = NULL;
5370 #endif
5371
5372         static GdkGeometry geometry;
5373
5374         g_return_val_if_fail(account != NULL, NULL);
5375
5376         debug_print("Creating compose window...\n");
5377         compose = g_new0(Compose, 1);
5378
5379         titles[COL_MIMETYPE] = _("MIME type");
5380         titles[COL_SIZE]     = _("Size");
5381         titles[COL_NAME]     = _("Name");
5382
5383         compose->account = account;
5384         
5385         compose->mutex = g_mutex_new();
5386         compose->set_cursor_pos = -1;
5387
5388         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5389         gtk_window_set_resizable(GTK_WINDOW(window), TRUE);
5390         gtk_widget_set_size_request(window, -1, prefs_common.compose_height);
5391
5392         if (!geometry.max_width) {
5393                 geometry.max_width = gdk_screen_width();
5394                 geometry.max_height = gdk_screen_height();
5395         }
5396
5397         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
5398                                       &geometry, GDK_HINT_MAX_SIZE);
5399         if (!geometry.min_width) {
5400                 geometry.min_width = 600;
5401                 geometry.min_height = 480;
5402         }
5403         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
5404                                       &geometry, GDK_HINT_MIN_SIZE);
5405         gtk_widget_set_uposition(window, prefs_common.compose_x, 
5406                                  prefs_common.compose_y);
5407
5408         g_signal_connect(G_OBJECT(window), "delete_event",
5409                          G_CALLBACK(compose_delete_cb), compose);
5410         MANAGE_WINDOW_SIGNALS_CONNECT(window);
5411         gtk_widget_realize(window);
5412
5413         gtkut_widget_set_composer_icon(window);
5414
5415         vbox = gtk_vbox_new(FALSE, 0);
5416         gtk_container_add(GTK_CONTAINER(window), vbox);
5417
5418         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
5419         menubar = menubar_create(window, compose_entries,
5420                                  n_menu_entries, "<Compose>", compose);
5421         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
5422
5423         if (prefs_common.toolbar_detachable) {
5424                 handlebox = gtk_handle_box_new();
5425         } else {
5426                 handlebox = gtk_hbox_new(FALSE, 0);
5427         }
5428         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
5429
5430         gtk_widget_realize(handlebox);
5431         compose->toolbar = toolbar_create(TOOLBAR_COMPOSE, handlebox,
5432                                           (gpointer)compose);
5433
5434         vbox2 = gtk_vbox_new(FALSE, 2);
5435         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
5436         gtk_container_set_border_width(GTK_CONTAINER(vbox2), 0);
5437         
5438         /* Notebook */
5439         notebook = gtk_notebook_new();
5440         gtk_widget_set_size_request(notebook, -1, 130);
5441         gtk_widget_show(notebook);
5442
5443         /* header labels and entries */
5444         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
5445         /* attachment list */
5446         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
5447         /* Others Tab */
5448         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
5449
5450         /* Subject */
5451         subject_hbox = gtk_hbox_new(FALSE, 0);
5452         gtk_widget_show(subject_hbox);
5453
5454         subject_frame = gtk_frame_new(NULL);
5455         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_NONE);
5456         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, 0);
5457         gtk_widget_show(subject_frame);
5458
5459         subject = gtk_hbox_new(FALSE, 0);
5460         gtk_container_set_border_width(GTK_CONTAINER(subject), 0);
5461         gtk_widget_show(subject);
5462
5463         label = gtk_label_new(_("Subject:"));
5464         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 0);
5465         gtk_widget_show(label);
5466
5467         subject_entry = gtk_entry_new();
5468         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 0);
5469         g_signal_connect_after(G_OBJECT(subject_entry), "grab_focus",
5470                          G_CALLBACK(compose_grab_focus_cb), compose);
5471         gtk_widget_show(subject_entry);
5472         compose->subject_entry = subject_entry;
5473         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
5474         
5475         edit_vbox = gtk_vbox_new(FALSE, 0);
5476
5477         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
5478
5479         /* ruler */
5480         ruler_hbox = gtk_hbox_new(FALSE, 0);
5481         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
5482
5483         ruler = gtk_shruler_new();
5484         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
5485         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
5486                            BORDER_WIDTH);
5487
5488         /* text widget */
5489         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
5490         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
5491                                        GTK_POLICY_AUTOMATIC,
5492                                        GTK_POLICY_AUTOMATIC);
5493         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwin),
5494                                             GTK_SHADOW_IN);
5495         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
5496         gtk_widget_set_size_request(scrolledwin, prefs_common.compose_width, -1);
5497
5498         text = gtk_text_view_new();
5499         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
5500         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD_CHAR);
5501         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), TRUE);
5502         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
5503         gtk_text_buffer_add_selection_clipboard(buffer, clipboard);
5504         
5505         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
5506
5507         g_signal_connect_after(G_OBJECT(text), "size_allocate",
5508                                G_CALLBACK(compose_edit_size_alloc),
5509                                ruler);
5510         g_signal_connect(G_OBJECT(buffer), "changed",
5511                          G_CALLBACK(compose_changed_cb), compose);
5512         g_signal_connect(G_OBJECT(text), "grab_focus",
5513                          G_CALLBACK(compose_grab_focus_cb), compose);
5514         g_signal_connect(G_OBJECT(buffer), "insert_text",
5515                          G_CALLBACK(text_inserted), compose);
5516         g_signal_connect(G_OBJECT(text), "button_press_event",
5517                          G_CALLBACK(text_clicked), compose);
5518         g_signal_connect(G_OBJECT(subject_entry), "changed",
5519                          G_CALLBACK(compose_changed_cb), compose);
5520
5521         /* drag and drop */
5522         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5523                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5524                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5525         g_signal_connect(G_OBJECT(text), "drag_data_received",
5526                          G_CALLBACK(compose_insert_drag_received_cb),
5527                          compose);
5528         g_signal_connect(G_OBJECT(text), "drag-drop",
5529                          G_CALLBACK(compose_drag_drop),
5530                          compose);
5531         gtk_widget_show_all(vbox);
5532
5533         /* pane between attach clist and text */
5534         paned = gtk_vpaned_new();
5535         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
5536         gtk_container_add(GTK_CONTAINER(vbox2), paned);
5537         gtk_paned_add1(GTK_PANED(paned), notebook);
5538         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
5539         gtk_widget_show_all(paned);
5540
5541
5542         if (prefs_common.textfont) {
5543                 PangoFontDescription *font_desc;
5544
5545                 font_desc = pango_font_description_from_string
5546                         (prefs_common.textfont);
5547                 if (font_desc) {
5548                         gtk_widget_modify_font(text, font_desc);
5549                         pango_font_description_free(font_desc);
5550                 }
5551         }
5552
5553         color[0] = quote_color;
5554         cmap = gdk_drawable_get_colormap(window->window);
5555         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
5556         if (success[0] == FALSE) {
5557                 GtkStyle *style;
5558
5559                 g_warning("Compose: color allocation failed.\n");
5560                 style = gtk_widget_get_style(text);
5561                 quote_color = style->black;
5562         }
5563
5564         n_entries = sizeof(compose_popup_entries) /
5565                 sizeof(compose_popup_entries[0]);
5566         popupmenu = menu_create_items(compose_popup_entries, n_entries,
5567                                       "<Compose>", &popupfactory,
5568                                       compose);
5569
5570         ifactory = gtk_item_factory_from_widget(menubar);
5571         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5572         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5573         menu_set_sensitive(ifactory, "/Options/Remove references", FALSE);
5574
5575         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5576
5577         undostruct = undo_init(text);
5578         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
5579                                    menubar);
5580
5581         address_completion_start(window);
5582
5583         compose->window        = window;
5584         compose->vbox          = vbox;
5585         compose->menubar       = menubar;
5586         compose->handlebox     = handlebox;
5587
5588         compose->vbox2         = vbox2;
5589
5590         compose->paned = paned;
5591
5592         compose->edit_vbox     = edit_vbox;
5593         compose->ruler_hbox    = ruler_hbox;
5594         compose->ruler         = ruler;
5595         compose->scrolledwin   = scrolledwin;
5596         compose->text          = text;
5597
5598         compose->focused_editable = NULL;
5599
5600         compose->popupmenu    = popupmenu;
5601         compose->popupfactory = popupfactory;
5602
5603         compose->tmpl_menu = tmpl_menu;
5604
5605         compose->mode = mode;
5606
5607         compose->targetinfo = NULL;
5608         compose->replyinfo  = NULL;
5609         compose->fwdinfo    = NULL;
5610
5611         compose->replyto     = NULL;
5612         compose->cc          = NULL;
5613         compose->bcc         = NULL;
5614         compose->followup_to = NULL;
5615
5616         compose->ml_post     = NULL;
5617
5618         compose->inreplyto   = NULL;
5619         compose->references  = NULL;
5620         compose->msgid       = NULL;
5621         compose->boundary    = NULL;
5622
5623         compose->autowrap       = prefs_common.autowrap;
5624
5625         compose->use_signing    = FALSE;
5626         compose->use_encryption = FALSE;
5627         compose->privacy_system = NULL;
5628
5629         compose->modified = FALSE;
5630
5631         compose->return_receipt = FALSE;
5632
5633         compose->to_list        = NULL;
5634         compose->newsgroup_list = NULL;
5635
5636         compose->undostruct = undostruct;
5637
5638         compose->sig_str = NULL;
5639
5640         compose->exteditor_file    = NULL;
5641         compose->exteditor_pid     = -1;
5642         compose->exteditor_tag     = -1;
5643         compose->draft_timeout_tag = -1;
5644
5645 #if USE_ASPELL
5646         menu_set_sensitive(ifactory, "/Spelling", FALSE);
5647         if (mode != COMPOSE_REDIRECT) {
5648                 if (prefs_common.enable_aspell && prefs_common.dictionary &&
5649                     strcmp(prefs_common.dictionary, _("None"))) {
5650                         gtkaspell = gtkaspell_new(prefs_common.aspell_path,
5651                                                   prefs_common.dictionary,
5652                                                   conv_get_locale_charset_str(),
5653                                                   prefs_common.misspelled_col,
5654                                                   prefs_common.check_while_typing,
5655                                                   prefs_common.use_alternate,
5656                                                   GTK_TEXT_VIEW(text),
5657                                                   GTK_WINDOW(compose->window));
5658                         if (!gtkaspell) {
5659                                 alertpanel_error(_("Spell checker could not "
5660                                                 "be started.\n%s"),
5661                                                 gtkaspell_checkers_strerror());
5662                                 gtkaspell_checkers_reset_error();
5663                         } else {
5664                                 if (!gtkaspell_set_sug_mode(gtkaspell,
5665                                                 prefs_common.aspell_sugmode)) {
5666                                         debug_print("Aspell: could not set "
5667                                                     "suggestion mode %s\n",
5668                                                     gtkaspell_checkers_strerror());
5669                                         gtkaspell_checkers_reset_error();
5670                                 }
5671
5672                                 menu_set_sensitive(ifactory, "/Spelling", TRUE);
5673                         }
5674                 }
5675         }
5676         compose->gtkaspell = gtkaspell;
5677 #endif
5678
5679         compose_select_account(compose, account, TRUE);
5680
5681         menu_set_active(ifactory, "/Edit/Auto wrapping", prefs_common.autowrap);
5682         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
5683                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
5684
5685         if (account->set_autobcc && account->auto_bcc && mode != COMPOSE_REEDIT) 
5686                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
5687         
5688         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
5689                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
5690
5691
5692         if (account->protocol != A_NNTP)
5693                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
5694         else
5695                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
5696
5697         addressbook_set_target_compose(compose);
5698         
5699         if (mode != COMPOSE_REDIRECT)
5700                 compose_set_template_menu(compose);
5701         else {
5702                 menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5703                 menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
5704         }
5705
5706         compose_list = g_list_append(compose_list, compose);
5707
5708         if (!prefs_common.show_ruler)
5709                 gtk_widget_hide(ruler_hbox);
5710                 
5711         menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Show ruler");
5712         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
5713                                        prefs_common.show_ruler);
5714
5715         /* Priority */
5716         compose->priority = PRIORITY_NORMAL;
5717         compose_update_priority_menu_item(compose);
5718
5719         compose_set_out_encoding(compose);
5720         
5721         /* Actions menu */
5722         compose_update_actions_menu(compose);
5723
5724         /* Privacy Systems menu */
5725         compose_update_privacy_systems_menu(compose);
5726
5727         activate_privacy_system(compose, account, TRUE);
5728         toolbar_set_style(compose->toolbar->toolbar, compose->handlebox, prefs_common.toolbar_style);
5729         gtk_widget_show(window);
5730         
5731         return compose;
5732 }
5733
5734 static GtkWidget *compose_account_option_menu_create(Compose *compose)
5735 {
5736         GList *accounts;
5737         GtkWidget *hbox;
5738         GtkWidget *optmenu;
5739         GtkWidget *menu;
5740         gint num = 0, def_menu = 0;
5741
5742         accounts = account_get_list();
5743         g_return_val_if_fail(accounts != NULL, NULL);
5744
5745         hbox = gtk_hbox_new(FALSE, 0);
5746         optmenu = gtk_option_menu_new();
5747         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5748         menu = gtk_menu_new();
5749
5750         for (; accounts != NULL; accounts = accounts->next, num++) {
5751                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
5752                 GtkWidget *menuitem;
5753                 gchar *name;
5754
5755                 if (ac == compose->account) def_menu = num;
5756
5757                 if (ac->name)
5758                         name = g_strdup_printf("%s: %s <%s>",
5759                                                ac->account_name,
5760                                                ac->name, ac->address);
5761                 else
5762                         name = g_strdup_printf("%s: %s",
5763                                                ac->account_name, ac->address);
5764                 MENUITEM_ADD(menu, menuitem, name, ac->account_id);
5765                 g_free(name);
5766                 g_signal_connect(G_OBJECT(menuitem), "activate",
5767                                  G_CALLBACK(account_activated),
5768                                  compose);
5769         }
5770
5771         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
5772         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
5773
5774         return hbox;
5775 }
5776
5777 static void compose_set_priority_cb(gpointer data,
5778                                     guint action,
5779                                     GtkWidget *widget)
5780 {
5781         Compose *compose = (Compose *) data;
5782         compose->priority = action;
5783 }
5784
5785 static void compose_update_priority_menu_item(Compose * compose)
5786 {
5787         GtkItemFactory *ifactory;
5788         GtkWidget *menuitem = NULL;
5789
5790         ifactory = gtk_item_factory_from_widget(compose->menubar);
5791         
5792         switch (compose->priority) {
5793                 case PRIORITY_HIGHEST:
5794                         menuitem = gtk_item_factory_get_item
5795                                 (ifactory, "/Options/Priority/Highest");
5796                         break;
5797                 case PRIORITY_HIGH:
5798                         menuitem = gtk_item_factory_get_item
5799                                 (ifactory, "/Options/Priority/High");
5800                         break;
5801                 case PRIORITY_NORMAL:
5802                         menuitem = gtk_item_factory_get_item
5803                                 (ifactory, "/Options/Priority/Normal");
5804                         break;
5805                 case PRIORITY_LOW:
5806                         menuitem = gtk_item_factory_get_item
5807                                 (ifactory, "/Options/Priority/Low");
5808                         break;
5809                 case PRIORITY_LOWEST:
5810                         menuitem = gtk_item_factory_get_item
5811                                 (ifactory, "/Options/Priority/Lowest");
5812                         break;
5813         }
5814         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5815 }       
5816
5817 static void compose_set_privacy_system_cb(GtkWidget *widget, gpointer data)
5818 {
5819         Compose *compose = (Compose *) data;
5820         gchar *systemid;
5821         GtkItemFactory *ifactory;
5822         gboolean can_sign = FALSE, can_encrypt = FALSE;
5823
5824         g_return_if_fail(GTK_IS_CHECK_MENU_ITEM(widget));
5825
5826         if (!GTK_CHECK_MENU_ITEM(widget)->active)
5827                 return;
5828
5829         systemid = g_object_get_data(G_OBJECT(widget), "privacy_system");
5830         g_free(compose->privacy_system);
5831         compose->privacy_system = NULL;
5832         if (systemid != NULL) {
5833                 compose->privacy_system = g_strdup(systemid);
5834
5835                 can_sign = privacy_system_can_sign(systemid);
5836                 can_encrypt = privacy_system_can_encrypt(systemid);
5837         }
5838
5839         debug_print("activated privacy system: %s\n", systemid != NULL ? systemid : "None");
5840
5841         ifactory = gtk_item_factory_from_widget(compose->menubar);
5842         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5843         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5844 }
5845
5846 static void compose_update_privacy_system_menu_item(Compose * compose, gboolean warn)
5847 {
5848         static gchar *branch_path = "/Options/Privacy System";
5849         GtkItemFactory *ifactory;
5850         GtkWidget *menuitem = NULL;
5851         GList *amenu;
5852         gboolean can_sign = FALSE, can_encrypt = FALSE;
5853         gboolean found = FALSE;
5854
5855         ifactory = gtk_item_factory_from_widget(compose->menubar);
5856
5857         if (compose->privacy_system != NULL) {
5858                 gchar *systemid;
5859
5860                 menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
5861                 g_return_if_fail(menuitem != NULL);
5862
5863                 amenu = GTK_MENU_SHELL(menuitem)->children;
5864                 menuitem = NULL;
5865                 while (amenu != NULL) {
5866                         GList *alist = amenu->next;
5867
5868                         systemid = g_object_get_data(G_OBJECT(amenu->data), "privacy_system");
5869                         if (systemid != NULL) {
5870                                 if (strcmp(systemid, compose->privacy_system) == 0) {
5871                                         menuitem = GTK_WIDGET(amenu->data);
5872
5873                                         can_sign = privacy_system_can_sign(systemid);
5874                                         can_encrypt = privacy_system_can_encrypt(systemid);
5875                                         found = TRUE;
5876                                         break;
5877                                 } 
5878                         } else if (strlen(compose->privacy_system) == 0) {
5879                                         menuitem = GTK_WIDGET(amenu->data);
5880
5881                                         can_sign = FALSE;
5882                                         can_encrypt = FALSE;
5883                                         found = TRUE;
5884                                         break;
5885                         }
5886
5887                         amenu = alist;
5888                 }
5889                 if (menuitem != NULL)
5890                         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5891                 
5892                 if (warn && !found && strlen(compose->privacy_system)) {
5893                         gchar *tmp = g_strdup_printf(
5894                                 _("The privacy system '%s' cannot be loaded. You "
5895                                   "will not be able to sign or encrypt this message."),
5896                                   compose->privacy_system);
5897                         alertpanel_warning(tmp);
5898                         g_free(tmp);
5899                 }
5900         } 
5901
5902         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5903         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5904 }       
5905  
5906 static void compose_set_out_encoding(Compose *compose)
5907 {
5908         GtkItemFactoryEntry *entry;
5909         GtkItemFactory *ifactory;
5910         CharSet out_encoding;
5911         gchar *path, *p, *q;
5912         GtkWidget *item;
5913
5914         out_encoding = conv_get_charset_from_str(prefs_common.outgoing_charset);
5915         ifactory = gtk_item_factory_from_widget(compose->menubar);
5916
5917         for (entry = compose_entries; entry->callback != compose_address_cb;
5918              entry++) {
5919                 if (entry->callback == compose_set_encoding_cb &&
5920                     (CharSet)entry->callback_action == out_encoding) {
5921                         p = q = path = g_strdup(entry->path);
5922                         while (*p) {
5923                                 if (*p == '_') {
5924                                         if (p[1] == '_') {
5925                                                 p++;
5926                                                 *q++ = '_';
5927                                         }
5928                                 } else
5929                                         *q++ = *p;
5930                                 p++;
5931                         }
5932                         *q = '\0';
5933                         item = gtk_item_factory_get_item(ifactory, path);
5934                         gtk_widget_activate(item);
5935                         g_free(path);
5936                         break;
5937                 }
5938         }
5939 }
5940
5941 static void compose_set_template_menu(Compose *compose)
5942 {
5943         GSList *tmpl_list, *cur;
5944         GtkWidget *menu;
5945         GtkWidget *item;
5946
5947         tmpl_list = template_get_config();
5948
5949         menu = gtk_menu_new();
5950
5951         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
5952                 Template *tmpl = (Template *)cur->data;
5953
5954                 item = gtk_menu_item_new_with_label(tmpl->name);
5955                 gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
5956                 g_signal_connect(G_OBJECT(item), "activate",
5957                                  G_CALLBACK(compose_template_activate_cb),
5958                                  compose);
5959                 g_object_set_data(G_OBJECT(item), "template", tmpl);
5960                 gtk_widget_show(item);
5961         }
5962
5963         gtk_widget_show(menu);
5964         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
5965 }
5966
5967 void compose_update_actions_menu(Compose *compose)
5968 {
5969         GtkItemFactory *ifactory;
5970
5971         ifactory = gtk_item_factory_from_widget(compose->menubar);
5972         action_update_compose_menu(ifactory, "/Tools/Actions", compose);
5973 }
5974
5975 void compose_update_privacy_systems_menu(Compose *compose)
5976 {
5977         static gchar *branch_path = "/Options/Privacy System";
5978         GtkItemFactory *ifactory;
5979         GtkWidget *menuitem;
5980         GSList *systems, *cur;
5981         GList *amenu;
5982         GtkWidget *widget;
5983         GtkWidget *system_none;
5984         GSList *group;
5985
5986         ifactory = gtk_item_factory_from_widget(compose->menubar);
5987
5988         /* remove old entries */
5989         menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
5990         g_return_if_fail(menuitem != NULL);
5991
5992         amenu = GTK_MENU_SHELL(menuitem)->children->next;
5993         while (amenu != NULL) {
5994                 GList *alist = amenu->next;
5995                 gtk_widget_destroy(GTK_WIDGET(amenu->data));
5996                 amenu = alist;
5997         }
5998
5999         system_none = gtk_item_factory_get_widget(ifactory,
6000                 "/Options/Privacy System/None");
6001
6002         g_signal_connect(G_OBJECT(system_none), "activate",
6003                 G_CALLBACK(compose_set_privacy_system_cb), compose);
6004
6005         systems = privacy_get_system_ids();
6006         for (cur = systems; cur != NULL; cur = g_slist_next(cur)) {
6007                 gchar *systemid = cur->data;
6008
6009                 group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(system_none));
6010                 widget = gtk_radio_menu_item_new_with_label(group,
6011                         privacy_system_get_name(systemid));
6012                 g_object_set_data_full(G_OBJECT(widget), "privacy_system",
6013                                        g_strdup(systemid), g_free);
6014                 g_signal_connect(G_OBJECT(widget), "activate",
6015                         G_CALLBACK(compose_set_privacy_system_cb), compose);
6016
6017                 gtk_menu_append(GTK_MENU(system_none->parent), widget);
6018                 gtk_widget_show(widget);
6019                 g_free(systemid);
6020         }
6021         g_slist_free(systems);
6022 }
6023
6024 void compose_reflect_prefs_all(void)
6025 {
6026         GList *cur;
6027         Compose *compose;
6028
6029         for (cur = compose_list; cur != NULL; cur = cur->next) {
6030                 compose = (Compose *)cur->data;
6031                 compose_set_template_menu(compose);
6032         }
6033 }
6034
6035 void compose_reflect_prefs_pixmap_theme(void)
6036 {
6037         GList *cur;
6038         Compose *compose;
6039
6040         for (cur = compose_list; cur != NULL; cur = cur->next) {
6041                 compose = (Compose *)cur->data;
6042                 toolbar_update(TOOLBAR_COMPOSE, compose);
6043         }
6044 }
6045
6046 static void compose_template_apply(Compose *compose, Template *tmpl,
6047                                    gboolean replace)
6048 {
6049         GtkTextView *text;
6050         GtkTextBuffer *buffer;
6051         GtkTextMark *mark;
6052         GtkTextIter iter;
6053         gchar *qmark;
6054         gchar *parsed_str = NULL;
6055         gint cursor_pos = 0;
6056         if (!tmpl) return;
6057
6058         text = GTK_TEXT_VIEW(compose->text);
6059         buffer = gtk_text_view_get_buffer(text);
6060
6061         if (tmpl->subject && *tmpl->subject != '\0')
6062                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
6063                                    tmpl->subject);
6064         if (tmpl->to && *tmpl->to != '\0')
6065                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
6066         if (tmpl->cc && *tmpl->cc != '\0')
6067                 compose_entry_append(compose, tmpl->cc, COMPOSE_CC);
6068
6069         if (tmpl->bcc && *tmpl->bcc != '\0')
6070                 compose_entry_append(compose, tmpl->bcc, COMPOSE_BCC);
6071
6072         if (replace)
6073                 gtk_text_buffer_set_text(buffer, "", -1);
6074
6075         mark = gtk_text_buffer_get_insert(buffer);
6076         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
6077
6078         if (tmpl->value) {
6079                 if ((compose->replyinfo == NULL) && (compose->fwdinfo == NULL)) {
6080                         parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
6081                                                        NULL, NULL, FALSE);
6082                 } else {
6083                         if (prefs_common.quotemark && *prefs_common.quotemark)
6084                                 qmark = prefs_common.quotemark;
6085                         else
6086                                 qmark = "> ";
6087
6088                         if (compose->replyinfo != NULL)
6089                                 parsed_str = compose_quote_fmt(compose, compose->replyinfo,
6090                                                                tmpl->value, qmark, NULL, FALSE);
6091                         else if (compose->fwdinfo != NULL)
6092                                 parsed_str = compose_quote_fmt(compose, compose->fwdinfo,
6093                                                                tmpl->value, qmark, NULL, FALSE);
6094                         else
6095                                 parsed_str = NULL;
6096                 }
6097         }
6098         if (replace && parsed_str && compose->account->auto_sig)
6099                 compose_insert_sig(compose, FALSE);
6100
6101         if (replace && parsed_str) {
6102                 gtk_text_buffer_get_start_iter(buffer, &iter);
6103                 gtk_text_buffer_place_cursor(buffer, &iter);
6104         }
6105         
6106         if (parsed_str) {
6107                 cursor_pos = quote_fmt_get_cursor_pos();
6108                 compose->set_cursor_pos = cursor_pos;
6109                 if (cursor_pos == -1)
6110                         cursor_pos = 0;
6111                 gtk_text_buffer_get_start_iter(buffer, &iter);
6112                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, cursor_pos);
6113                 gtk_text_buffer_place_cursor(buffer, &iter);
6114         }
6115
6116         compose_changed_cb(NULL, compose);
6117 }
6118
6119 static void compose_destroy(Compose *compose)
6120 {
6121         compose_list = g_list_remove(compose_list, compose);
6122
6123         /* NOTE: address_completion_end() does nothing with the window
6124          * however this may change. */
6125         address_completion_end(compose->window);
6126
6127         slist_free_strings(compose->to_list);
6128         g_slist_free(compose->to_list);
6129         slist_free_strings(compose->newsgroup_list);
6130         g_slist_free(compose->newsgroup_list);
6131         slist_free_strings(compose->header_list);
6132         g_slist_free(compose->header_list);
6133
6134         procmsg_msginfo_free(compose->targetinfo);
6135         procmsg_msginfo_free(compose->replyinfo);
6136         procmsg_msginfo_free(compose->fwdinfo);
6137
6138         g_free(compose->replyto);
6139         g_free(compose->cc);
6140         g_free(compose->bcc);
6141         g_free(compose->newsgroups);
6142         g_free(compose->followup_to);
6143
6144         g_free(compose->ml_post);
6145
6146         g_free(compose->inreplyto);
6147         g_free(compose->references);
6148         g_free(compose->msgid);
6149         g_free(compose->boundary);
6150
6151         if (compose->redirect_filename)
6152                 g_free(compose->redirect_filename);
6153         if (compose->undostruct)
6154                 undo_destroy(compose->undostruct);
6155
6156         g_free(compose->sig_str);
6157
6158         g_free(compose->exteditor_file);
6159
6160         g_free(compose->orig_charset);
6161
6162         g_free(compose->privacy_system);
6163
6164         if (addressbook_get_target_compose() == compose)
6165                 addressbook_set_target_compose(NULL);
6166
6167 #if USE_ASPELL
6168         if (compose->gtkaspell) {
6169                 gtkaspell_delete(compose->gtkaspell);
6170                 compose->gtkaspell = NULL;
6171         }
6172 #endif
6173
6174         prefs_common.compose_width = compose->scrolledwin->allocation.width;
6175         prefs_common.compose_height = compose->window->allocation.height;
6176
6177         if (!gtk_widget_get_parent(compose->paned))
6178                 gtk_widget_destroy(compose->paned);
6179         gtk_widget_destroy(compose->popupmenu);
6180
6181         gtk_widget_destroy(compose->window);
6182         toolbar_destroy(compose->toolbar);
6183         g_free(compose->toolbar);
6184         g_mutex_free(compose->mutex);
6185         g_free(compose);
6186 }
6187
6188 static void compose_attach_info_free(AttachInfo *ainfo)
6189 {
6190         g_free(ainfo->file);
6191         g_free(ainfo->content_type);
6192         g_free(ainfo->name);
6193         g_free(ainfo);
6194 }
6195
6196 static void compose_attach_remove_selected(Compose *compose)
6197 {
6198         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
6199         GtkTreeSelection *selection;
6200         GList *sel, *cur;
6201         GtkTreeModel *model;
6202
6203         selection = gtk_tree_view_get_selection(tree_view);
6204         sel = gtk_tree_selection_get_selected_rows(selection, &model);
6205
6206         if (!sel) 
6207                 return;
6208
6209         for (cur = sel; cur != NULL; cur = cur->next) {
6210                 GtkTreePath *path = cur->data;
6211                 GtkTreeRowReference *ref = gtk_tree_row_reference_new
6212                                                 (model, cur->data);
6213                 cur->data = ref;
6214                 gtk_tree_path_free(path);
6215         }
6216
6217         for (cur = sel; cur != NULL; cur = cur->next) {
6218                 GtkTreeRowReference *ref = cur->data;
6219                 GtkTreePath *path = gtk_tree_row_reference_get_path(ref);
6220                 GtkTreeIter iter;
6221
6222                 if (gtk_tree_model_get_iter(model, &iter, path))
6223                         gtk_list_store_remove(GTK_LIST_STORE(model), &iter);
6224                 
6225                 gtk_tree_path_free(path);
6226                 gtk_tree_row_reference_free(ref);
6227         }
6228
6229         g_list_free(sel);
6230 }
6231
6232 static struct _AttachProperty
6233 {
6234         GtkWidget *window;
6235         GtkWidget *mimetype_entry;
6236         GtkWidget *encoding_optmenu;
6237         GtkWidget *path_entry;
6238         GtkWidget *filename_entry;
6239         GtkWidget *ok_btn;
6240         GtkWidget *cancel_btn;
6241 } attach_prop;
6242
6243 static void gtk_tree_path_free_(gpointer ptr, gpointer data)
6244 {       
6245         gtk_tree_path_free((GtkTreePath *)ptr);
6246 }
6247
6248 static void compose_attach_property(Compose *compose)
6249 {
6250         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
6251         AttachInfo *ainfo;
6252         GtkOptionMenu *optmenu;
6253         GtkTreeSelection *selection;
6254         GList *sel;
6255         GtkTreeModel *model;
6256         GtkTreeIter iter;
6257         GtkTreePath *path;
6258         static gboolean cancelled;
6259
6260         /* only if one selected */
6261         selection = gtk_tree_view_get_selection(tree_view);
6262         if (gtk_tree_selection_count_selected_rows(selection) != 1) 
6263                 return;
6264
6265         sel = gtk_tree_selection_get_selected_rows(selection, &model);
6266         if (!sel)
6267                 return;
6268
6269         path = (GtkTreePath *) sel->data;
6270         gtk_tree_model_get_iter(model, &iter, path);
6271         gtk_tree_model_get(model, &iter, COL_DATA, &ainfo, -1); 
6272         
6273         if (!ainfo) {
6274                 g_list_foreach(sel, gtk_tree_path_free_, NULL);
6275                 g_list_free(sel);
6276                 return;
6277         }               
6278         g_list_free(sel);
6279
6280         if (!attach_prop.window)
6281                 compose_attach_property_create(&cancelled);
6282         gtk_widget_grab_focus(attach_prop.ok_btn);
6283         gtk_widget_show(attach_prop.window);
6284         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
6285
6286         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
6287         if (ainfo->encoding == ENC_UNKNOWN)
6288                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
6289                                     GINT_TO_POINTER(ENC_BASE64));
6290         else
6291                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
6292                                     GINT_TO_POINTER(ainfo->encoding));
6293
6294         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
6295                            ainfo->content_type ? ainfo->content_type : "");
6296         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
6297                            ainfo->file ? ainfo->file : "");
6298         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
6299                            ainfo->name ? ainfo->name : "");
6300
6301         for (;;) {
6302                 const gchar *entry_text;
6303                 gchar *text;
6304                 gchar *cnttype = NULL;
6305                 gchar *file = NULL;
6306                 off_t size = 0;
6307                 GtkWidget *menu;
6308                 GtkWidget *menuitem;
6309
6310                 cancelled = FALSE;
6311                 gtk_main();
6312
6313                 gtk_widget_hide(attach_prop.window);
6314                 
6315                 if (cancelled) 
6316                         break;
6317
6318                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
6319                 if (*entry_text != '\0') {
6320                         gchar *p;
6321
6322                         text = g_strstrip(g_strdup(entry_text));
6323                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
6324                                 cnttype = g_strdup(text);
6325                                 g_free(text);
6326                         } else {
6327                                 alertpanel_error(_("Invalid MIME type."));
6328                                 g_free(text);
6329                                 continue;
6330                         }
6331                 }
6332
6333                 menu = gtk_option_menu_get_menu(optmenu);
6334                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
6335                 ainfo->encoding = GPOINTER_TO_INT
6336                         (g_object_get_data(G_OBJECT(menuitem), MENU_VAL_ID));
6337
6338                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
6339                 if (*entry_text != '\0') {
6340                         if (is_file_exist(entry_text) &&
6341                             (size = get_file_size(entry_text)) > 0)
6342                                 file = g_strdup(entry_text);
6343                         else {
6344                                 alertpanel_error
6345                                         (_("File doesn't exist or is empty."));
6346                                 g_free(cnttype);
6347                                 continue;
6348                         }
6349                 }
6350
6351                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
6352                 if (*entry_text != '\0') {
6353                         g_free(ainfo->name);
6354                         ainfo->name = g_strdup(entry_text);
6355                 }
6356
6357                 if (cnttype) {
6358                         g_free(ainfo->content_type);
6359                         ainfo->content_type = cnttype;
6360                 }
6361                 if (file) {
6362                         g_free(ainfo->file);
6363                         ainfo->file = file;
6364                 }
6365                 if (size)
6366                         ainfo->size = size;
6367
6368                 /* update tree store */
6369                 text = to_human_readable(ainfo->size);
6370                 gtk_tree_model_get_iter(model, &iter, path);
6371                 gtk_list_store_set(GTK_LIST_STORE(model), &iter,
6372                                    COL_MIMETYPE, ainfo->content_type,
6373                                    COL_SIZE, text,
6374                                    COL_NAME, ainfo->name,
6375                                    -1);
6376                 
6377                 break;
6378         }
6379
6380         gtk_tree_path_free(path);
6381 }
6382
6383 #define SET_LABEL_AND_ENTRY(str, entry, top) \
6384 { \
6385         label = gtk_label_new(str); \
6386         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
6387                          GTK_FILL, 0, 0, 0); \
6388         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
6389  \
6390         entry = gtk_entry_new(); \
6391         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
6392                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
6393 }
6394
6395 static void compose_attach_property_create(gboolean *cancelled)
6396 {
6397         GtkWidget *window;
6398         GtkWidget *vbox;
6399         GtkWidget *table;
6400         GtkWidget *label;
6401         GtkWidget *mimetype_entry;
6402         GtkWidget *hbox;
6403         GtkWidget *optmenu;
6404         GtkWidget *optmenu_menu;
6405         GtkWidget *menuitem;
6406         GtkWidget *path_entry;
6407         GtkWidget *filename_entry;
6408         GtkWidget *hbbox;
6409         GtkWidget *ok_btn;
6410         GtkWidget *cancel_btn;
6411         GList     *mime_type_list, *strlist;
6412
6413         debug_print("Creating attach_property window...\n");
6414
6415         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
6416         gtk_widget_set_size_request(window, 480, -1);
6417         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
6418         gtk_window_set_title(GTK_WINDOW(window), _("Properties"));
6419         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
6420         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
6421         g_signal_connect(G_OBJECT(window), "delete_event",
6422                          G_CALLBACK(attach_property_delete_event),
6423                          cancelled);
6424         g_signal_connect(G_OBJECT(window), "key_press_event",
6425                          G_CALLBACK(attach_property_key_pressed),
6426                          cancelled);
6427
6428         vbox = gtk_vbox_new(FALSE, 8);
6429         gtk_container_add(GTK_CONTAINER(window), vbox);
6430
6431         table = gtk_table_new(4, 2, FALSE);
6432         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
6433         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
6434         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
6435
6436         label = gtk_label_new(_("MIME type")); 
6437         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
6438                          GTK_FILL, 0, 0, 0); 
6439         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
6440         mimetype_entry = gtk_combo_new(); 
6441         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
6442                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
6443                          
6444         /* stuff with list */
6445         mime_type_list = procmime_get_mime_type_list();
6446         strlist = NULL;
6447         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
6448                 MimeType *type = (MimeType *) mime_type_list->data;
6449                 gchar *tmp;
6450
6451                 tmp = g_strdup_printf("%s/%s", type->type, type->sub_type);
6452
6453                 if (g_list_find_custom(strlist, tmp, (GCompareFunc)strcmp2))
6454                         g_free(tmp);
6455                 else
6456                         strlist = g_list_insert_sorted(strlist, (gpointer)tmp,
6457                                         (GCompareFunc)strcmp2);
6458         }
6459
6460         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
6461
6462         for (mime_type_list = strlist; mime_type_list != NULL; 
6463                 mime_type_list = mime_type_list->next)
6464                 g_free(mime_type_list->data);
6465         g_list_free(strlist);
6466                          
6467         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
6468
6469         label = gtk_label_new(_("Encoding"));
6470         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
6471                          GTK_FILL, 0, 0, 0);
6472         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
6473
6474         hbox = gtk_hbox_new(FALSE, 0);
6475         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
6476                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
6477
6478         optmenu = gtk_option_menu_new();
6479         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
6480
6481         optmenu_menu = gtk_menu_new();
6482         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
6483         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6484         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
6485         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6486         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable",
6487                      ENC_QUOTED_PRINTABLE);
6488         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6489
6490         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
6491
6492         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6493
6494         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
6495         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
6496
6497         gtkut_stock_button_set_create(&hbbox, &cancel_btn, GTK_STOCK_CANCEL,
6498                                       &ok_btn, GTK_STOCK_OK,
6499                                       NULL, NULL);
6500         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
6501         gtk_widget_grab_default(ok_btn);
6502
6503         g_signal_connect(G_OBJECT(ok_btn), "clicked",
6504                          G_CALLBACK(attach_property_ok),
6505                          cancelled);
6506         g_signal_connect(G_OBJECT(cancel_btn), "clicked",
6507                          G_CALLBACK(attach_property_cancel),
6508                          cancelled);
6509
6510         gtk_widget_show_all(vbox);
6511
6512         attach_prop.window           = window;
6513         attach_prop.mimetype_entry   = mimetype_entry;
6514         attach_prop.encoding_optmenu = optmenu;
6515         attach_prop.path_entry       = path_entry;
6516         attach_prop.filename_entry   = filename_entry;
6517         attach_prop.ok_btn           = ok_btn;
6518         attach_prop.cancel_btn       = cancel_btn;
6519 }
6520
6521 #undef SET_LABEL_AND_ENTRY
6522
6523 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
6524 {
6525         *cancelled = FALSE;
6526         gtk_main_quit();
6527 }
6528
6529 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
6530 {
6531         *cancelled = TRUE;
6532         gtk_main_quit();
6533 }
6534
6535 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
6536                                          gboolean *cancelled)
6537 {
6538         *cancelled = TRUE;
6539         gtk_main_quit();
6540
6541         return TRUE;
6542 }
6543
6544 static gboolean attach_property_key_pressed(GtkWidget *widget,
6545                                             GdkEventKey *event,
6546                                             gboolean *cancelled)
6547 {
6548         if (event && event->keyval == GDK_Escape) {
6549                 *cancelled = TRUE;
6550                 gtk_main_quit();
6551         }
6552         return FALSE;
6553 }
6554
6555 static void compose_exec_ext_editor(Compose *compose)
6556 {
6557 #ifdef G_OS_UNIX
6558         gchar *tmp;
6559         pid_t pid;
6560         gint pipe_fds[2];
6561
6562         tmp = g_strdup_printf("%s%ctmpmsg.%p", get_tmp_dir(),
6563                               G_DIR_SEPARATOR, compose);
6564
6565         if (pipe(pipe_fds) < 0) {
6566                 perror("pipe");
6567                 g_free(tmp);
6568                 return;
6569         }
6570
6571         if ((pid = fork()) < 0) {
6572                 perror("fork");
6573                 g_free(tmp);
6574                 return;
6575         }
6576
6577         if (pid != 0) {
6578                 /* close the write side of the pipe */
6579                 close(pipe_fds[1]);
6580
6581                 compose->exteditor_file    = g_strdup(tmp);
6582                 compose->exteditor_pid     = pid;
6583
6584                 compose_set_ext_editor_sensitive(compose, FALSE);
6585
6586                 compose->exteditor_ch = g_io_channel_unix_new(pipe_fds[0]);
6587                 compose->exteditor_tag = g_io_add_watch(compose->exteditor_ch,
6588                                                         G_IO_IN,
6589                                                         compose_input_cb,
6590                                                         compose);
6591         } else {        /* process-monitoring process */
6592                 pid_t pid_ed;
6593
6594                 if (setpgid(0, 0))
6595                         perror("setpgid");
6596
6597                 /* close the read side of the pipe */
6598                 close(pipe_fds[0]);
6599
6600                 if (compose_write_body_to_file(compose, tmp) < 0) {
6601                         fd_write_all(pipe_fds[1], "2\n", 2);
6602                         _exit(1);
6603                 }
6604
6605                 pid_ed = compose_exec_ext_editor_real(tmp);
6606                 if (pid_ed < 0) {
6607                         fd_write_all(pipe_fds[1], "1\n", 2);
6608                         _exit(1);
6609                 }
6610
6611                 /* wait until editor is terminated */
6612                 waitpid(pid_ed, NULL, 0);
6613
6614                 fd_write_all(pipe_fds[1], "0\n", 2);
6615
6616                 close(pipe_fds[1]);
6617                 _exit(0);
6618         }
6619
6620         g_free(tmp);
6621 #endif /* G_OS_UNIX */
6622 }
6623
6624 #ifdef G_OS_UNIX
6625 static gint compose_exec_ext_editor_real(const gchar *file)
6626 {
6627         static gchar *def_cmd = "emacs %s";
6628         gchar buf[1024];
6629         gchar *p;
6630         gchar **cmdline;
6631         pid_t pid;
6632
6633         g_return_val_if_fail(file != NULL, -1);
6634
6635         if ((pid = fork()) < 0) {
6636                 perror("fork");
6637                 return -1;
6638         }
6639
6640         if (pid != 0) return pid;
6641
6642         /* grandchild process */
6643
6644         if (setpgid(0, getppid()))
6645                 perror("setpgid");
6646
6647         if (prefs_common.ext_editor_cmd &&
6648             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
6649             *(p + 1) == 's' && !strchr(p + 2, '%')) {
6650                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
6651         } else {
6652                 if (prefs_common.ext_editor_cmd)
6653                         g_warning("External editor command line is invalid: '%s'\n",
6654                                   prefs_common.ext_editor_cmd);
6655                 g_snprintf(buf, sizeof(buf), def_cmd, file);
6656         }
6657
6658         cmdline = strsplit_with_quote(buf, " ", 1024);
6659         execvp(cmdline[0], cmdline);
6660
6661         perror("execvp");
6662         g_strfreev(cmdline);
6663
6664         _exit(1);
6665 }
6666
6667 static gboolean compose_ext_editor_kill(Compose *compose)
6668 {
6669         pid_t pgid = compose->exteditor_pid * -1;
6670         gint ret;
6671
6672         ret = kill(pgid, 0);
6673
6674         if (ret == 0 || (ret == -1 && EPERM == errno)) {
6675                 AlertValue val;
6676                 gchar *msg;
6677
6678                 msg = g_strdup_printf
6679                         (_("The external editor is still working.\n"
6680                            "Force terminating the process?\n"
6681                            "process group id: %d"), -pgid);
6682                 val = alertpanel_full(_("Notice"), msg, GTK_STOCK_NO, GTK_STOCK_YES,
6683                                       NULL, FALSE, NULL, ALERT_WARNING, G_ALERTDEFAULT);
6684                         
6685                 g_free(msg);
6686
6687                 if (val == G_ALERTALTERNATE) {
6688                         g_source_remove(compose->exteditor_tag);
6689                         g_io_channel_shutdown(compose->exteditor_ch,
6690                                               FALSE, NULL);
6691                         g_io_channel_unref(compose->exteditor_ch);
6692
6693                         if (kill(pgid, SIGTERM) < 0) perror("kill");
6694                         waitpid(compose->exteditor_pid, NULL, 0);
6695
6696                         g_warning("Terminated process group id: %d", -pgid);
6697                         g_warning("Temporary file: %s",
6698                                   compose->exteditor_file);
6699
6700                         compose_set_ext_editor_sensitive(compose, TRUE);
6701
6702                         g_free(compose->exteditor_file);
6703                         compose->exteditor_file    = NULL;
6704                         compose->exteditor_pid     = -1;
6705                         compose->exteditor_ch      = NULL;
6706                         compose->exteditor_tag     = -1;
6707                 } else
6708                         return FALSE;
6709         }
6710
6711         return TRUE;
6712 }
6713
6714 static gboolean compose_input_cb(GIOChannel *source, GIOCondition condition,
6715                                  gpointer data)
6716 {
6717         gchar buf[3] = "3";
6718         Compose *compose = (Compose *)data;
6719         gsize bytes_read;
6720
6721         debug_print(_("Compose: input from monitoring process\n"));
6722
6723         g_io_channel_read_chars(source, buf, sizeof(buf), &bytes_read, NULL);
6724
6725         g_io_channel_shutdown(source, FALSE, NULL);
6726         g_io_channel_unref(source);
6727
6728         waitpid(compose->exteditor_pid, NULL, 0);
6729
6730         if (buf[0] == '0') {            /* success */
6731                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
6732                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
6733
6734                 gtk_text_buffer_set_text(buffer, "", -1);
6735                 compose_insert_file(compose, compose->exteditor_file);
6736                 compose_changed_cb(NULL, compose);
6737
6738                 if (g_unlink(compose->exteditor_file) < 0)
6739                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
6740         } else if (buf[0] == '1') {     /* failed */
6741                 g_warning("Couldn't exec external editor\n");
6742                 if (g_unlink(compose->exteditor_file) < 0)
6743                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
6744         } else if (buf[0] == '2') {
6745                 g_warning("Couldn't write to file\n");
6746         } else if (buf[0] == '3') {
6747                 g_warning("Pipe read failed\n");
6748         }
6749
6750         compose_set_ext_editor_sensitive(compose, TRUE);
6751
6752         g_free(compose->exteditor_file);
6753         compose->exteditor_file    = NULL;
6754         compose->exteditor_pid     = -1;
6755         compose->exteditor_ch      = NULL;
6756         compose->exteditor_tag     = -1;
6757
6758         return FALSE;
6759 }
6760
6761 static void compose_set_ext_editor_sensitive(Compose *compose,
6762                                              gboolean sensitive)
6763 {
6764         GtkItemFactory *ifactory;
6765
6766         ifactory = gtk_item_factory_from_widget(compose->menubar);
6767
6768         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
6769         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
6770         menu_set_sensitive(ifactory, "/Message/Insert file", sensitive);
6771         menu_set_sensitive(ifactory, "/Message/Insert signature", sensitive);
6772         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
6773         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
6774         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
6775                            sensitive);
6776
6777         gtk_widget_set_sensitive(compose->text,                   sensitive);
6778         gtk_widget_set_sensitive(compose->toolbar->send_btn,      sensitive);
6779         gtk_widget_set_sensitive(compose->toolbar->sendl_btn,     sensitive);
6780         gtk_widget_set_sensitive(compose->toolbar->draft_btn,     sensitive);
6781         gtk_widget_set_sensitive(compose->toolbar->insert_btn,    sensitive);
6782         gtk_widget_set_sensitive(compose->toolbar->sig_btn,       sensitive);
6783         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, sensitive);
6784         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn,  sensitive);
6785         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn,  sensitive);
6786 }
6787 #endif /* G_OS_UNIX */
6788
6789 /**
6790  * compose_undo_state_changed:
6791  *
6792  * Change the sensivity of the menuentries undo and redo
6793  **/
6794 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
6795                                        gint redo_state, gpointer data)
6796 {
6797         GtkWidget *widget = GTK_WIDGET(data);
6798         GtkItemFactory *ifactory;
6799
6800         g_return_if_fail(widget != NULL);
6801
6802         ifactory = gtk_item_factory_from_widget(widget);
6803
6804         switch (undo_state) {
6805         case UNDO_STATE_TRUE:
6806                 if (!undostruct->undo_state) {
6807                         undostruct->undo_state = TRUE;
6808                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
6809                 }
6810                 break;
6811         case UNDO_STATE_FALSE:
6812                 if (undostruct->undo_state) {
6813                         undostruct->undo_state = FALSE;
6814                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
6815                 }
6816                 break;
6817         case UNDO_STATE_UNCHANGED:
6818                 break;
6819         case UNDO_STATE_REFRESH:
6820                 menu_set_sensitive(ifactory, "/Edit/Undo",
6821                                    undostruct->undo_state);
6822                 break;
6823         default:
6824                 g_warning("Undo state not recognized");
6825                 break;
6826         }
6827
6828         switch (redo_state) {
6829         case UNDO_STATE_TRUE:
6830                 if (!undostruct->redo_state) {
6831                         undostruct->redo_state = TRUE;
6832                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
6833                 }
6834                 break;
6835         case UNDO_STATE_FALSE:
6836                 if (undostruct->redo_state) {
6837                         undostruct->redo_state = FALSE;
6838                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
6839                 }
6840                 break;
6841         case UNDO_STATE_UNCHANGED:
6842                 break;
6843         case UNDO_STATE_REFRESH:
6844                 menu_set_sensitive(ifactory, "/Edit/Redo",
6845                                    undostruct->redo_state);
6846                 break;
6847         default:
6848                 g_warning("Redo state not recognized");
6849                 break;
6850         }
6851 }
6852
6853 /* callback functions */
6854
6855 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
6856  * includes "non-client" (windows-izm) in calculation, so this calculation
6857  * may not be accurate.
6858  */
6859 static gboolean compose_edit_size_alloc(GtkEditable *widget,
6860                                         GtkAllocation *allocation,
6861                                         GtkSHRuler *shruler)
6862 {
6863         if (prefs_common.show_ruler) {
6864                 gint char_width = 0, char_height = 0;
6865                 gint line_width_in_chars;
6866
6867                 gtkut_get_font_size(GTK_WIDGET(widget),
6868                                     &char_width, &char_height);
6869                 line_width_in_chars =
6870                         (allocation->width - allocation->x) / char_width;
6871
6872                 /* got the maximum */
6873                 gtk_ruler_set_range(GTK_RULER(shruler),
6874                                     0.0, line_width_in_chars, 0,
6875                                     /*line_width_in_chars*/ char_width);
6876         }
6877
6878         return TRUE;
6879 }
6880
6881 static void account_activated(GtkMenuItem *menuitem, gpointer data)
6882 {
6883         Compose *compose = (Compose *)data;
6884
6885         PrefsAccount *ac;
6886         gchar *folderidentifier;
6887
6888         ac = account_find_from_id(
6889                 GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menuitem), MENU_VAL_ID)));
6890         g_return_if_fail(ac != NULL);
6891
6892         if (ac != compose->account)
6893                 compose_select_account(compose, ac, FALSE);
6894
6895         /* Set message save folder */
6896         if (account_get_special_folder(compose->account, F_OUTBOX)) {
6897                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
6898         }
6899         g_signal_connect(G_OBJECT(compose->savemsg_checkbtn), "toggled",
6900                          G_CALLBACK(compose_savemsg_checkbtn_cb), compose);
6901                            
6902         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
6903         if (account_get_special_folder(compose->account, F_OUTBOX)) {
6904                 folderidentifier = folder_item_get_identifier(account_get_special_folder
6905                                   (compose->account, F_OUTBOX));
6906                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
6907                 g_free(folderidentifier);
6908         }
6909 }
6910
6911 static void attach_selected(GtkTreeView *tree_view, GtkTreePath *tree_path,
6912                             GtkTreeViewColumn *column, Compose *compose)
6913 {
6914         compose_attach_property(compose);
6915 }
6916
6917 static gboolean attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
6918                                       gpointer data)
6919 {
6920         Compose *compose = (Compose *)data;
6921         GtkTreeSelection *attach_selection;
6922         gint attach_nr_selected;
6923         GtkItemFactory *ifactory;
6924         
6925         if (!event) return FALSE;
6926
6927         if (event->button == 3) {
6928                 attach_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget));
6929                 attach_nr_selected = gtk_tree_selection_count_selected_rows(attach_selection);
6930                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6931                         
6932                 if (attach_nr_selected > 0)
6933                 {
6934                         menu_set_sensitive(ifactory, "/Remove", TRUE);
6935                         menu_set_sensitive(ifactory, "/Properties...", TRUE);
6936                 } else {
6937                         menu_set_sensitive(ifactory, "/Remove", FALSE);
6938                         menu_set_sensitive(ifactory, "/Properties...", FALSE);
6939                 }
6940                         
6941                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
6942                                NULL, NULL, event->button, event->time);
6943                 return TRUE;                           
6944         }
6945
6946         return FALSE;
6947 }
6948
6949 static gboolean attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
6950                                    gpointer data)
6951 {
6952         Compose *compose = (Compose *)data;
6953
6954         if (!event) return FALSE;
6955
6956         switch (event->keyval) {
6957         case GDK_Delete:
6958                 compose_attach_remove_selected(compose);
6959                 break;
6960         }
6961         return FALSE;
6962 }
6963
6964 static void compose_allow_user_actions (Compose *compose, gboolean allow)
6965 {
6966         GtkItemFactory *ifactory = gtk_item_factory_from_widget(compose->menubar);
6967         toolbar_comp_set_sensitive(compose, allow);
6968         menu_set_sensitive(ifactory, "/Message", allow);
6969         menu_set_sensitive(ifactory, "/Edit", allow);
6970 #if USE_ASPELL
6971         menu_set_sensitive(ifactory, "/Spelling", allow);
6972 #endif  
6973         menu_set_sensitive(ifactory, "/Options", allow);
6974         menu_set_sensitive(ifactory, "/Tools", allow);
6975         menu_set_sensitive(ifactory, "/Help", allow);
6976         
6977         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), allow);
6978
6979 }
6980
6981 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
6982 {
6983         Compose *compose = (Compose *)data;
6984         
6985         if (prefs_common.work_offline && !inc_offline_should_override())
6986                 return;
6987         
6988         if (compose->draft_timeout_tag != -1) { /* CLAWS: disable draft timeout */
6989                 gtk_timeout_remove(compose->draft_timeout_tag);
6990                 compose->draft_timeout_tag = -1;
6991         }
6992
6993         compose_send(compose);
6994 }
6995
6996 static void compose_send_later_cb(gpointer data, guint action,
6997                                   GtkWidget *widget)
6998 {
6999         Compose *compose = (Compose *)data;
7000         gint val;
7001
7002         val = compose_queue_sub(compose, NULL, NULL, TRUE);
7003         if (!val) 
7004                 compose_close(compose);
7005         else if (val == -2) {
7006                 alertpanel_error(_("Could not queue message:\n\n%s."), strerror(errno));
7007         }
7008 }
7009
7010 void compose_draft (gpointer data) 
7011 {
7012         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);     
7013 }
7014
7015 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
7016 {
7017         Compose *compose = (Compose *)data;
7018         FolderItem *draft;
7019         gchar *tmp;
7020         gint msgnum;
7021         MsgFlags flag = {0, 0};
7022         static gboolean lock = FALSE;
7023         MsgInfo *newmsginfo;
7024         FILE *fp;
7025         gboolean target_locked = FALSE;
7026         
7027         if (lock) return;
7028
7029         draft = account_get_special_folder(compose->account, F_DRAFT);
7030         g_return_if_fail(draft != NULL);
7031         
7032         if (!g_mutex_trylock(compose->mutex)) {
7033                 /* we don't want to lock the mutex once it's available,
7034                  * because as the only other part of compose.c locking
7035                  * it is compose_close - which means once unlocked,
7036                  * the compose struct will be freed */
7037                 debug_print("couldn't lock mutex, probably sending\n");
7038                 return;
7039         }
7040         
7041         lock = TRUE;
7042
7043         tmp = g_strdup_printf("%s%cdraft.%p", get_tmp_dir(),
7044                               G_DIR_SEPARATOR, compose);
7045         if ((fp = g_fopen(tmp, "wb")) == NULL) {
7046                 FILE_OP_ERROR(tmp, "fopen");
7047                 goto unlock;
7048         }
7049
7050         /* chmod for security */
7051         if (change_file_mode_rw(fp, tmp) < 0) {
7052                 FILE_OP_ERROR(tmp, "chmod");
7053                 g_warning("can't change file mode\n");
7054         }
7055
7056         /* Save draft infos */
7057         fprintf(fp, "X-Sylpheed-Account-Id:%d\n", compose->account->account_id);
7058         fprintf(fp, "S:%s\n", compose->account->address);
7059         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
7060                 gchar *savefolderid;
7061
7062                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
7063                 fprintf(fp, "SCF:%s\n", savefolderid);
7064                 g_free(savefolderid);
7065         }
7066         if (compose->return_receipt) {
7067                 fprintf(fp, "RRCPT:1\n");
7068         }
7069         if (compose->privacy_system) {
7070                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
7071                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
7072                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
7073         }
7074         fprintf(fp, "\n");
7075
7076         if (compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_STORE) < 0) {
7077                 fclose(fp);
7078                 g_unlink(tmp);
7079                 g_free(tmp);
7080                 goto unlock;
7081         }
7082         fclose(fp);
7083         
7084         if (compose->targetinfo) {
7085                 target_locked = MSG_IS_LOCKED(compose->targetinfo->flags);
7086                 flag.perm_flags = target_locked?MSG_LOCKED:0;
7087         }
7088
7089         folder_item_scan(draft);
7090         if ((msgnum = folder_item_add_msg(draft, tmp, &flag, TRUE)) < 0) {
7091                 g_unlink(tmp);
7092                 g_free(tmp);
7093                 if (action != COMPOSE_AUTO_SAVE)
7094                         alertpanel_error(_("Could not save draft."));
7095                 goto unlock;
7096         }
7097         g_free(tmp);
7098         draft->mtime = 0;       /* force updating */
7099
7100         if (compose->mode == COMPOSE_REEDIT) {
7101                 compose_remove_reedit_target(compose, TRUE);
7102         }
7103
7104         newmsginfo = folder_item_get_msginfo(draft, msgnum);
7105         if (newmsginfo) {
7106                 procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
7107                 if (target_locked)
7108                         procmsg_msginfo_set_flags(newmsginfo, MSG_LOCKED, MSG_DRAFT);
7109                 else
7110                         procmsg_msginfo_set_flags(newmsginfo, 0, MSG_DRAFT);
7111                 if (compose_use_attach(compose))
7112                         procmsg_msginfo_set_flags(newmsginfo, 0,
7113                                                   MSG_HAS_ATTACHMENT);
7114
7115                 procmsg_msginfo_free(newmsginfo);
7116         }
7117         
7118         folder_item_scan(draft);
7119         
7120         if (action == COMPOSE_QUIT_EDITING) {
7121                 lock = FALSE;
7122                 g_mutex_unlock(compose->mutex); /* must be done before closing */
7123                 compose_close(compose);
7124                 return;
7125         } else {
7126                 struct stat s;
7127                 gchar *path;
7128
7129                 path = folder_item_fetch_msg(draft, msgnum);
7130                 if (path == NULL) {
7131                         debug_print("can't fetch %s:%d\n",draft->path, msgnum);
7132                         goto unlock;
7133                 }
7134                 if (g_stat(path, &s) < 0) {
7135                         FILE_OP_ERROR(path, "stat");
7136                         g_free(path);
7137                         goto unlock;
7138                 }
7139                 g_free(path);
7140
7141                 procmsg_msginfo_free(compose->targetinfo);
7142                 compose->targetinfo = procmsg_msginfo_new();
7143                 compose->targetinfo->msgnum = msgnum;
7144                 compose->targetinfo->size = s.st_size;
7145                 compose->targetinfo->mtime = s.st_mtime;
7146                 compose->targetinfo->folder = draft;
7147                 if (target_locked)
7148                         procmsg_msginfo_set_flags(compose->targetinfo, MSG_LOCKED, 0);
7149                 compose->mode = COMPOSE_REEDIT;
7150                 
7151                 if (action == COMPOSE_AUTO_SAVE) {
7152                         compose->autosaved_draft = compose->targetinfo;
7153                 }
7154                 compose->modified = FALSE;
7155                 compose_set_title(compose);
7156         }
7157 unlock:
7158         lock = FALSE;
7159         g_mutex_unlock(compose->mutex);
7160 }
7161
7162 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
7163 {
7164         Compose *compose = (Compose *)data;
7165         GList *file_list;
7166
7167         if (compose->redirect_filename != NULL)
7168                 return;
7169
7170         file_list = filesel_select_multiple_files_open(_("Select file"));
7171
7172         if (file_list) {
7173                 GList *tmp;
7174
7175                 for ( tmp = file_list; tmp; tmp = tmp->next) {
7176                         gchar *file = (gchar *) tmp->data;
7177                         gchar *utf8_filename = conv_filename_to_utf8(file);
7178                         compose_attach_append(compose, file, utf8_filename, NULL);
7179                         compose_changed_cb(NULL, compose);
7180                         g_free(file);
7181                         g_free(utf8_filename);
7182                 }
7183                 g_list_free(file_list);
7184         }               
7185 }
7186
7187 static void compose_insert_file_cb(gpointer data, guint action,
7188                                    GtkWidget *widget)
7189 {
7190         Compose *compose = (Compose *)data;
7191         GList *file_list;
7192
7193         file_list = filesel_select_multiple_files_open(_("Select file"));
7194
7195         if (file_list) {
7196                 GList *tmp;
7197
7198                 for ( tmp = file_list; tmp; tmp = tmp->next) {
7199                         gchar *file = (gchar *) tmp->data;
7200                         gchar *filedup = g_strdup(file);
7201                         gchar *shortfile = g_path_get_basename(filedup);
7202                         ComposeInsertResult res;
7203
7204                         res = compose_insert_file(compose, file);
7205                         if (res == COMPOSE_INSERT_READ_ERROR) {
7206                                 alertpanel_error(_("File '%s' could not be read."), shortfile);
7207                         } else if (res == COMPOSE_INSERT_INVALID_CHARACTER) {
7208                                 alertpanel_error(_("File '%s' contained invalid characters\n"
7209                                                    "for the current encoding, insertion may be incorrect."), shortfile);
7210                         }
7211                         g_free(shortfile);
7212                         g_free(filedup);
7213                         g_free(file);
7214                 }
7215                 g_list_free(file_list);
7216         }
7217 }
7218
7219 static void compose_insert_sig_cb(gpointer data, guint action,
7220                                   GtkWidget *widget)
7221 {
7222         Compose *compose = (Compose *)data;
7223
7224         compose_insert_sig(compose, FALSE);
7225 }
7226
7227 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
7228                               gpointer data)
7229 {
7230         gint x, y;
7231         Compose *compose = (Compose *)data;
7232
7233         gtkut_widget_get_uposition(widget, &x, &y);
7234         prefs_common.compose_x = x;
7235         prefs_common.compose_y = y;
7236
7237         if (compose->sending)
7238                 return TRUE;
7239         compose_close_cb(compose, 0, NULL);
7240         return TRUE;
7241 }
7242
7243 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
7244 {
7245         Compose *compose = (Compose *)data;
7246         AlertValue val;
7247
7248 #ifdef G_OS_UNIX
7249         if (compose->exteditor_tag != -1) {
7250                 if (!compose_ext_editor_kill(compose))
7251                         return;
7252         }
7253 #endif
7254
7255         if (compose->modified) {
7256                 val = alertpanel(_("Discard message"),
7257                                  _("This message has been modified. Discard it?"),
7258                                  _("_Discard"), _("_Save to Drafts"), GTK_STOCK_CANCEL);
7259
7260                 switch (val) {
7261                 case G_ALERTDEFAULT:
7262                         if (prefs_common.autosave)
7263                                 compose_remove_draft(compose);                  
7264                         break;
7265                 case G_ALERTALTERNATE:
7266                         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);
7267                         return;
7268                 default:
7269                         return;
7270                 }
7271         }
7272
7273         compose_close(compose);
7274 }
7275
7276 static void compose_set_encoding_cb(gpointer data, guint action,
7277                                     GtkWidget *widget)
7278 {
7279         Compose *compose = (Compose *)data;
7280
7281         if (GTK_CHECK_MENU_ITEM(widget)->active)
7282                 compose->out_encoding = (CharSet)action;
7283 }
7284
7285 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
7286 {
7287         Compose *compose = (Compose *)data;
7288
7289         addressbook_open(compose);
7290 }
7291
7292 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
7293 {
7294         Compose *compose = (Compose *)data;
7295         Template *tmpl;
7296         gchar *msg;
7297         AlertValue val;
7298
7299         tmpl = g_object_get_data(G_OBJECT(widget), "template");
7300         g_return_if_fail(tmpl != NULL);
7301
7302         msg = g_strdup_printf(_("Do you want to apply the template '%s' ?"),
7303                               tmpl->name);
7304         val = alertpanel(_("Apply template"), msg,
7305                          _("_Replace"), _("_Insert"), GTK_STOCK_CANCEL);
7306         g_free(msg);
7307
7308         if (val == G_ALERTDEFAULT)
7309                 compose_template_apply(compose, tmpl, TRUE);
7310         else if (val == G_ALERTALTERNATE)
7311                 compose_template_apply(compose, tmpl, FALSE);
7312 }
7313
7314 static void compose_ext_editor_cb(gpointer data, guint action,
7315                                   GtkWidget *widget)
7316 {
7317         Compose *compose = (Compose *)data;
7318
7319         compose_exec_ext_editor(compose);
7320 }
7321
7322 static void compose_undo_cb(Compose *compose)
7323 {
7324         gboolean prev_autowrap = compose->autowrap;
7325
7326         compose->autowrap = FALSE;
7327         undo_undo(compose->undostruct);
7328         compose->autowrap = prev_autowrap;
7329 }
7330
7331 static void compose_redo_cb(Compose *compose)
7332 {
7333         gboolean prev_autowrap = compose->autowrap;
7334         
7335         compose->autowrap = FALSE;
7336         undo_redo(compose->undostruct);
7337         compose->autowrap = prev_autowrap;
7338 }
7339
7340 static void entry_cut_clipboard(GtkWidget *entry)
7341 {
7342         if (GTK_IS_EDITABLE(entry))
7343                 gtk_editable_cut_clipboard (GTK_EDITABLE(entry));
7344         else if (GTK_IS_TEXT_VIEW(entry))
7345                 gtk_text_buffer_cut_clipboard(
7346                         gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry)),
7347                         gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),
7348                         TRUE);
7349 }
7350
7351 static void entry_copy_clipboard(GtkWidget *entry)
7352 {
7353         if (GTK_IS_EDITABLE(entry))
7354                 gtk_editable_copy_clipboard (GTK_EDITABLE(entry));
7355         else if (GTK_IS_TEXT_VIEW(entry))
7356                 gtk_text_buffer_copy_clipboard(
7357                         gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry)),
7358                         gtk_clipboard_get(GDK_SELECTION_CLIPBOARD));
7359 }
7360
7361 static void entry_paste_clipboard(Compose *compose, GtkWidget *entry, 
7362                                   gboolean wrap, GdkAtom clip)
7363 {
7364         if (GTK_IS_TEXT_VIEW(entry)) {
7365                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry));
7366                 GtkTextMark *mark_start = gtk_text_buffer_get_insert(buffer);
7367                 GtkTextIter start_iter, end_iter;
7368                 gint start, end;
7369                 
7370                 gchar *contents = gtk_clipboard_wait_for_text(gtk_clipboard_get(clip));
7371
7372                 if (contents == NULL)
7373                         return;
7374
7375                 gtk_text_buffer_delete_selection(buffer, FALSE, TRUE);
7376                 gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark_start);
7377                 
7378                 start = gtk_text_iter_get_offset(&start_iter);
7379
7380                 gtk_text_buffer_insert(buffer, &start_iter, contents, strlen(contents));
7381                 
7382                 if (!wrap) {
7383                         end = start + strlen(contents);
7384                         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start);
7385                         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end);
7386                         gtk_text_buffer_apply_tag_by_name(buffer, "no_wrap", &start_iter, &end_iter);
7387                 } else if (wrap && clip == GDK_SELECTION_PRIMARY) {
7388                         mark_start = gtk_text_buffer_get_insert(buffer);
7389                         gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark_start);
7390                         gtk_text_iter_backward_char(&start_iter);
7391                         compose_beautify_paragraph(compose, &start_iter, TRUE);
7392                 }
7393                 
7394         } else if (GTK_IS_EDITABLE(entry))
7395                 gtk_editable_paste_clipboard (GTK_EDITABLE(entry));
7396         
7397 }
7398
7399 static void entry_allsel(GtkWidget *entry)
7400 {
7401         if (GTK_IS_EDITABLE(entry))
7402                 gtk_editable_select_region(GTK_EDITABLE(entry), 0, -1);
7403         else if (GTK_IS_TEXT_VIEW(entry)) {
7404                 GtkTextIter startiter, enditer;
7405                 GtkTextBuffer *textbuf;
7406
7407                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry));
7408                 gtk_text_buffer_get_start_iter(textbuf, &startiter);
7409                 gtk_text_buffer_get_end_iter(textbuf, &enditer);
7410
7411                 gtk_text_buffer_move_mark_by_name(textbuf, 
7412                         "selection_bound", &startiter);
7413                 gtk_text_buffer_move_mark_by_name(textbuf, 
7414                         "insert", &enditer);
7415         }
7416 }
7417
7418 static void compose_cut_cb(Compose *compose)
7419 {
7420         if (compose->focused_editable &&
7421             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7422                 entry_cut_clipboard(compose->focused_editable);
7423 }
7424
7425 static void compose_copy_cb(Compose *compose)
7426 {
7427         if (compose->focused_editable &&
7428             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7429                 entry_copy_clipboard(compose->focused_editable);
7430 }
7431
7432 static void compose_paste_cb(Compose *compose)
7433 {
7434         gint prev_autowrap;
7435         GtkTextBuffer *buffer;
7436         BLOCK_WRAP();
7437         if (compose->focused_editable &&
7438             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7439                 entry_paste_clipboard(compose, compose->focused_editable, 
7440                                 prefs_common.linewrap_pastes,
7441                                 GDK_SELECTION_CLIPBOARD);
7442         UNBLOCK_WRAP();
7443 }
7444
7445 static void compose_paste_as_quote_cb(Compose *compose)
7446 {
7447         gint wrap_quote = prefs_common.linewrap_quote;
7448         if (compose->focused_editable &&
7449             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
7450                 /* let text_insert() (called directly or at a later time
7451                  * after the gtk_editable_paste_clipboard) know that 
7452                  * text is to be inserted as a quotation. implemented
7453                  * by using a simple refcount... */
7454                 gint paste_as_quotation = GPOINTER_TO_INT(g_object_get_data(
7455                                                 G_OBJECT(compose->focused_editable),
7456                                                 "paste_as_quotation"));
7457                 g_object_set_data(G_OBJECT(compose->focused_editable),
7458                                     "paste_as_quotation",
7459                                     GINT_TO_POINTER(paste_as_quotation + 1));
7460                 prefs_common.linewrap_quote = prefs_common.linewrap_pastes;
7461                 entry_paste_clipboard(compose, compose->focused_editable, 
7462                                 prefs_common.linewrap_pastes,
7463                                 GDK_SELECTION_CLIPBOARD);
7464                 prefs_common.linewrap_quote = wrap_quote;
7465         }
7466 }
7467
7468 static void compose_paste_no_wrap_cb(Compose *compose)
7469 {
7470         gint prev_autowrap;
7471         GtkTextBuffer *buffer;
7472         BLOCK_WRAP();
7473         if (compose->focused_editable &&
7474             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7475                 entry_paste_clipboard(compose, compose->focused_editable, FALSE,
7476                         GDK_SELECTION_CLIPBOARD);
7477         UNBLOCK_WRAP();
7478 }
7479
7480 static void compose_paste_wrap_cb(Compose *compose)
7481 {
7482         gint prev_autowrap;
7483         GtkTextBuffer *buffer;
7484         BLOCK_WRAP();
7485         if (compose->focused_editable &&
7486             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7487                 entry_paste_clipboard(compose, compose->focused_editable, TRUE,
7488                         GDK_SELECTION_CLIPBOARD);
7489         UNBLOCK_WRAP();
7490 }
7491
7492 static void compose_allsel_cb(Compose *compose)
7493 {
7494         if (compose->focused_editable &&
7495             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7496                 entry_allsel(compose->focused_editable);
7497 }
7498
7499 static void textview_move_beginning_of_line (GtkTextView *text)
7500 {
7501         GtkTextBuffer *buffer;
7502         GtkTextMark *mark;
7503         GtkTextIter ins;
7504
7505         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7506
7507         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7508         mark = gtk_text_buffer_get_insert(buffer);
7509         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7510         gtk_text_iter_set_line_offset(&ins, 0);
7511         gtk_text_buffer_place_cursor(buffer, &ins);
7512 }
7513
7514 static void textview_move_forward_character (GtkTextView *text)
7515 {
7516         GtkTextBuffer *buffer;
7517         GtkTextMark *mark;
7518         GtkTextIter ins;
7519
7520         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7521
7522         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7523         mark = gtk_text_buffer_get_insert(buffer);
7524         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7525         if (gtk_text_iter_forward_cursor_position(&ins))
7526                 gtk_text_buffer_place_cursor(buffer, &ins);
7527 }
7528
7529 static void textview_move_backward_character (GtkTextView *text)
7530 {
7531         GtkTextBuffer *buffer;
7532         GtkTextMark *mark;
7533         GtkTextIter ins;
7534
7535         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7536
7537         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7538         mark = gtk_text_buffer_get_insert(buffer);
7539         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7540         if (gtk_text_iter_backward_cursor_position(&ins))
7541                 gtk_text_buffer_place_cursor(buffer, &ins);
7542 }
7543
7544 static void textview_move_forward_word (GtkTextView *text)
7545 {
7546         GtkTextBuffer *buffer;
7547         GtkTextMark *mark;
7548         GtkTextIter ins;
7549         gint count;
7550
7551         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7552
7553         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7554         mark = gtk_text_buffer_get_insert(buffer);
7555         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7556         count = gtk_text_iter_inside_word (&ins) ? 2 : 1;
7557         if (gtk_text_iter_forward_word_ends(&ins, count)) {
7558                 gtk_text_iter_backward_word_start(&ins);
7559                 gtk_text_buffer_place_cursor(buffer, &ins);
7560         }
7561 }
7562
7563 static void textview_move_backward_word (GtkTextView *text)
7564 {
7565         GtkTextBuffer *buffer;
7566         GtkTextMark *mark;
7567         GtkTextIter ins;
7568         gint count;
7569
7570         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7571
7572         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7573         mark = gtk_text_buffer_get_insert(buffer);
7574         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7575         count = gtk_text_iter_inside_word (&ins) ? 2 : 1;
7576         if (gtk_text_iter_backward_word_starts(&ins, 1))
7577                 gtk_text_buffer_place_cursor(buffer, &ins);
7578 }
7579
7580 static void textview_move_end_of_line (GtkTextView *text)
7581 {
7582         GtkTextBuffer *buffer;
7583         GtkTextMark *mark;
7584         GtkTextIter ins;
7585
7586         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7587
7588         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7589         mark = gtk_text_buffer_get_insert(buffer);
7590         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7591         if (gtk_text_iter_forward_to_line_end(&ins))
7592                 gtk_text_buffer_place_cursor(buffer, &ins);
7593 }
7594
7595 static void textview_move_next_line (GtkTextView *text)
7596 {
7597         GtkTextBuffer *buffer;
7598         GtkTextMark *mark;
7599         GtkTextIter ins;
7600         gint offset;
7601
7602         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7603
7604         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7605         mark = gtk_text_buffer_get_insert(buffer);
7606         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7607         offset = gtk_text_iter_get_line_offset(&ins);
7608         if (gtk_text_iter_forward_line(&ins)) {
7609                 gtk_text_iter_set_line_offset(&ins, offset);
7610                 gtk_text_buffer_place_cursor(buffer, &ins);
7611         }
7612 }
7613
7614 static void textview_move_previous_line (GtkTextView *text)
7615 {
7616         GtkTextBuffer *buffer;
7617         GtkTextMark *mark;
7618         GtkTextIter ins;
7619         gint offset;
7620
7621         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7622
7623         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7624         mark = gtk_text_buffer_get_insert(buffer);
7625         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7626         offset = gtk_text_iter_get_line_offset(&ins);
7627         if (gtk_text_iter_backward_line(&ins)) {
7628                 gtk_text_iter_set_line_offset(&ins, offset);
7629                 gtk_text_buffer_place_cursor(buffer, &ins);
7630         }
7631 }
7632
7633 static void textview_delete_forward_character (GtkTextView *text)
7634 {
7635         GtkTextBuffer *buffer;
7636         GtkTextMark *mark;
7637         GtkTextIter ins, end_iter;
7638
7639         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7640
7641         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7642         mark = gtk_text_buffer_get_insert(buffer);
7643         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7644         end_iter = ins;
7645         if (gtk_text_iter_forward_char(&end_iter)) {
7646                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7647         }
7648 }
7649
7650 static void textview_delete_backward_character (GtkTextView *text)
7651 {
7652         GtkTextBuffer *buffer;
7653         GtkTextMark *mark;
7654         GtkTextIter ins, end_iter;
7655
7656         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7657
7658         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7659         mark = gtk_text_buffer_get_insert(buffer);
7660         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7661         end_iter = ins;
7662         if (gtk_text_iter_backward_char(&end_iter)) {
7663                 gtk_text_buffer_delete(buffer, &end_iter, &ins);
7664         }
7665 }
7666
7667 static void textview_delete_forward_word (GtkTextView *text)
7668 {
7669         GtkTextBuffer *buffer;
7670         GtkTextMark *mark;
7671         GtkTextIter ins, end_iter;
7672
7673         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7674
7675         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7676         mark = gtk_text_buffer_get_insert(buffer);
7677         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7678         end_iter = ins;
7679         if (gtk_text_iter_forward_word_end(&end_iter)) {
7680                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7681         }
7682 }
7683
7684 static void textview_delete_backward_word (GtkTextView *text)
7685 {
7686         GtkTextBuffer *buffer;
7687         GtkTextMark *mark;
7688         GtkTextIter ins, end_iter;
7689
7690         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7691
7692         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7693         mark = gtk_text_buffer_get_insert(buffer);
7694         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7695         end_iter = ins;
7696         if (gtk_text_iter_backward_word_start(&end_iter)) {
7697                 gtk_text_buffer_delete(buffer, &end_iter, &ins);
7698         }
7699 }
7700
7701 static void textview_delete_line (GtkTextView *text)
7702 {
7703         GtkTextBuffer *buffer;
7704         GtkTextMark *mark;
7705         GtkTextIter ins, start_iter, end_iter;
7706         gboolean found;
7707
7708         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7709
7710         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7711         mark = gtk_text_buffer_get_insert(buffer);
7712         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7713
7714         start_iter = ins;
7715         gtk_text_iter_set_line_offset(&start_iter, 0);
7716
7717         end_iter = ins;
7718         if (gtk_text_iter_ends_line(&end_iter))
7719                 found = gtk_text_iter_forward_char(&end_iter);
7720         else
7721                 found = gtk_text_iter_forward_to_line_end(&end_iter);
7722
7723         if (found)
7724                 gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
7725 }
7726
7727 static void textview_delete_to_line_end (GtkTextView *text)
7728 {
7729         GtkTextBuffer *buffer;
7730         GtkTextMark *mark;
7731         GtkTextIter ins, end_iter;
7732         gboolean found;
7733
7734         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7735
7736         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7737         mark = gtk_text_buffer_get_insert(buffer);
7738         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7739         end_iter = ins;
7740         if (gtk_text_iter_ends_line(&end_iter))
7741                 found = gtk_text_iter_forward_char(&end_iter);
7742         else
7743                 found = gtk_text_iter_forward_to_line_end(&end_iter);
7744         if (found)
7745                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7746 }
7747
7748 static void compose_advanced_action_cb(Compose *compose,
7749                                         ComposeCallAdvancedAction action)
7750 {
7751         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
7752         static struct {
7753                 void (*do_action) (GtkTextView *text);
7754         } action_table[] = {
7755                 {textview_move_beginning_of_line},
7756                 {textview_move_forward_character},
7757                 {textview_move_backward_character},
7758                 {textview_move_forward_word},
7759                 {textview_move_backward_word},
7760                 {textview_move_end_of_line},
7761                 {textview_move_next_line},
7762                 {textview_move_previous_line},
7763                 {textview_delete_forward_character},
7764                 {textview_delete_backward_character},
7765                 {textview_delete_forward_word},
7766                 {textview_delete_backward_word},
7767                 {textview_delete_line},
7768                 {NULL}, /* gtk_stext_delete_line_n */
7769                 {textview_delete_to_line_end}
7770         };
7771
7772         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
7773
7774         if (action >= COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE &&
7775             action <= COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END) {
7776                 if (action_table[action].do_action)
7777                         action_table[action].do_action(text);
7778                 else
7779                         g_warning("Not implemented yet.");
7780         }
7781 }
7782
7783 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
7784 {
7785         gchar *str = NULL;
7786         
7787         if (GTK_IS_EDITABLE(widget)) {
7788                 str = gtk_editable_get_chars(GTK_EDITABLE(widget), 0, -1);
7789                 gtk_editable_set_position(GTK_EDITABLE(widget), 
7790                         strlen(str));
7791                 g_free(str);
7792                 if (widget->parent && widget->parent->parent
7793                  && widget->parent->parent->parent) {
7794                         if (GTK_IS_SCROLLED_WINDOW(widget->parent->parent->parent)) {
7795                                 gint y = widget->allocation.y;
7796                                 gint height = widget->allocation.height;
7797                                 GtkAdjustment *shown = gtk_scrolled_window_get_vadjustment
7798                                         (GTK_SCROLLED_WINDOW(widget->parent->parent->parent));
7799
7800                                 if (y < (int)shown->value) {
7801                                         gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), y - 1);
7802                                 }
7803                                 if (y + height > (int)shown->value + (int)shown->page_size) {
7804                                         if (y - height - 1 < (int)shown->upper - (int)shown->page_size) {
7805                                                 gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), 
7806                                                         y + height - (int)shown->page_size - 1);
7807                                         } else {
7808                                                 gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), 
7809                                                         (int)shown->upper - (int)shown->page_size - 1);
7810                                         }
7811                                 }
7812                         }
7813                 }
7814         }
7815
7816         if (GTK_IS_EDITABLE(widget) || GTK_IS_TEXT_VIEW(widget))
7817                 compose->focused_editable = widget;
7818 }
7819
7820 static void compose_changed_cb(GtkTextBuffer *textbuf, Compose *compose)
7821 {
7822         compose->modified = TRUE;
7823         compose_set_title(compose);
7824 }
7825
7826 static void compose_wrap_cb(gpointer data, guint action, GtkWidget *widget)
7827 {
7828         Compose *compose = (Compose *)data;
7829
7830         if (action == 1)
7831                 compose_wrap_all_full(compose, TRUE);
7832         else
7833                 compose_beautify_paragraph(compose, NULL, TRUE);
7834 }
7835
7836 static void compose_toggle_autowrap_cb(gpointer data, guint action,
7837                                        GtkWidget *widget)
7838 {
7839         Compose *compose = (Compose *)data;
7840         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
7841         if (compose->autowrap)
7842                 compose_wrap_all_full(compose, TRUE);
7843         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
7844 }
7845
7846 static void compose_toggle_sign_cb(gpointer data, guint action,
7847                                    GtkWidget *widget)
7848 {
7849         Compose *compose = (Compose *)data;
7850
7851         if (GTK_CHECK_MENU_ITEM(widget)->active)
7852                 compose->use_signing = TRUE;
7853         else
7854                 compose->use_signing = FALSE;
7855 }
7856
7857 static void compose_toggle_encrypt_cb(gpointer data, guint action,
7858                                       GtkWidget *widget)
7859 {
7860         Compose *compose = (Compose *)data;
7861
7862         if (GTK_CHECK_MENU_ITEM(widget)->active)
7863                 compose->use_encryption = TRUE;
7864         else
7865                 compose->use_encryption = FALSE;
7866 }
7867
7868 static void activate_privacy_system(Compose *compose, PrefsAccount *account, gboolean warn) 
7869 {
7870         g_free(compose->privacy_system);
7871
7872         compose->privacy_system = g_strdup(account->default_privacy_system);
7873         compose_update_privacy_system_menu_item(compose, warn);
7874 }
7875
7876 static void compose_toggle_ruler_cb(gpointer data, guint action,
7877                                     GtkWidget *widget)
7878 {
7879         Compose *compose = (Compose *)data;
7880
7881         if (GTK_CHECK_MENU_ITEM(widget)->active) {
7882                 gtk_widget_show(compose->ruler_hbox);
7883                 prefs_common.show_ruler = TRUE;
7884         } else {
7885                 gtk_widget_hide(compose->ruler_hbox);
7886                 gtk_widget_queue_resize(compose->edit_vbox);
7887                 prefs_common.show_ruler = FALSE;
7888         }
7889 }
7890
7891 static void compose_attach_drag_received_cb (GtkWidget          *widget,
7892                                              GdkDragContext     *drag_context,
7893                                              gint                x,
7894                                              gint                y,
7895                                              GtkSelectionData   *data,
7896                                              guint               info,
7897                                              guint               time,
7898                                              gpointer            user_data)
7899 {
7900         Compose *compose = (Compose *)user_data;
7901         GList *list, *tmp;
7902
7903         if (gdk_atom_name(data->type) && 
7904             !strcmp(gdk_atom_name(data->type), "text/uri-list")) {
7905                 list = uri_list_extract_filenames((const gchar *)data->data);
7906                 for (tmp = list; tmp != NULL; tmp = tmp->next)
7907                         compose_attach_append
7908                                 (compose, (const gchar *)tmp->data,
7909                                  (const gchar *)tmp->data, NULL);
7910                 if (list) compose_changed_cb(NULL, compose);
7911                 list_free_strings(list);
7912                 g_list_free(list);
7913         } else if (gdk_atom_name(data->type) && 
7914                    !strcmp(gdk_atom_name(data->type), "text/plain") &&
7915                    data->data && !strcmp(data->data, "Dummy-Summaryview")) {
7916                 /* comes from our summaryview */
7917                 SummaryView * summaryview = NULL;
7918                 GSList * list = NULL, *cur = NULL;
7919                 
7920                 if (mainwindow_get_mainwindow())
7921                         summaryview = mainwindow_get_mainwindow()->summaryview;
7922                 
7923                 if (summaryview)
7924                         list = summary_get_selected_msg_list(summaryview);
7925                 
7926                 for (cur = list; cur; cur = cur->next) {
7927                         MsgInfo *msginfo = (MsgInfo *)cur->data;
7928                         gchar *file = NULL;
7929                         if (msginfo)
7930                                 file = procmsg_get_message_file_full(msginfo, 
7931                                         TRUE, TRUE);
7932                         if (file) {
7933                                 compose_attach_append(compose, (const gchar *)file, 
7934                                         (const gchar *)file, "message/rfc822");
7935                                 g_free(file);
7936                         }
7937                 }
7938                 g_slist_free(list);
7939         }
7940 }
7941
7942 static gboolean compose_drag_drop(GtkWidget *widget,
7943                                   GdkDragContext *drag_context,
7944                                   gint x, gint y,
7945                                   guint time, gpointer user_data)
7946 {
7947         /* not handling this signal makes compose_insert_drag_received_cb
7948          * called twice */
7949         return TRUE;                                     
7950 }
7951
7952 static void compose_insert_drag_received_cb (GtkWidget          *widget,
7953                                              GdkDragContext     *drag_context,
7954                                              gint                x,
7955                                              gint                y,
7956                                              GtkSelectionData   *data,
7957                                              guint               info,
7958                                              guint               time,
7959                                              gpointer            user_data)
7960 {
7961         Compose *compose = (Compose *)user_data;
7962         GList *list, *tmp;
7963
7964         /* strangely, testing data->type == gdk_atom_intern("text/uri-list", TRUE)
7965          * does not work */
7966         if (gdk_atom_name(data->type) && !strcmp(gdk_atom_name(data->type), "text/uri-list")) {
7967                 list = uri_list_extract_filenames((const gchar *)data->data);
7968                 for (tmp = list; tmp != NULL; tmp = tmp->next) {
7969                         compose_insert_file(compose, (const gchar *)tmp->data);
7970                 }
7971                 list_free_strings(list);
7972                 g_list_free(list);
7973                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
7974                 return;
7975         } else {
7976 #if GTK_CHECK_VERSION(2, 8, 0)
7977                 /* do nothing, handled by GTK */
7978 #else
7979                 gchar *tmpfile = get_tmp_file();
7980                 str_write_to_file((const gchar *)data->data, tmpfile);
7981                 compose_insert_file(compose, tmpfile);
7982                 g_unlink(tmpfile);
7983                 g_free(tmpfile);
7984                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
7985 #endif
7986                 return;
7987         }
7988         gtk_drag_finish(drag_context, TRUE, FALSE, time);
7989 }
7990
7991 static void compose_header_drag_received_cb (GtkWidget          *widget,
7992                                              GdkDragContext     *drag_context,
7993                                              gint                x,
7994                                              gint                y,
7995                                              GtkSelectionData   *data,
7996                                              guint               info,
7997                                              guint               time,
7998                                              gpointer            user_data)
7999 {
8000         GtkEditable *entry = (GtkEditable *)user_data;
8001         gchar *email = (gchar *)data->data;
8002
8003         /* strangely, testing data->type == gdk_atom_intern("text/plain", TRUE)
8004          * does not work */
8005
8006         if (!strncmp(email, "mailto:", strlen("mailto:"))) {
8007                 gchar *decoded=g_new(gchar, strlen(email));
8008                 int start = 0;
8009
8010                 email += strlen("mailto:");
8011                 decode_uri(decoded, email); /* will fit */
8012                 gtk_editable_delete_text(entry, 0, -1);
8013                 gtk_editable_insert_text(entry, decoded, strlen(decoded), &start);
8014                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8015                 g_free(decoded);
8016                 return;
8017         }
8018         gtk_drag_finish(drag_context, TRUE, FALSE, time);
8019 }
8020
8021 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
8022                                              GtkWidget *widget)
8023 {
8024         Compose *compose = (Compose *)data;
8025
8026         if (GTK_CHECK_MENU_ITEM(widget)->active)
8027                 compose->return_receipt = TRUE;
8028         else
8029                 compose->return_receipt = FALSE;
8030 }
8031
8032 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
8033                                              GtkWidget *widget)
8034 {
8035         Compose *compose = (Compose *)data;
8036
8037         if (GTK_CHECK_MENU_ITEM(widget)->active)
8038                 compose->remove_references = TRUE;
8039         else
8040                 compose->remove_references = FALSE;
8041 }
8042
8043 gboolean compose_headerentry_key_press_event_cb(GtkWidget *entry,
8044                                             GdkEventKey *event,
8045                                             ComposeHeaderEntry *headerentry)
8046 {
8047         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
8048             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
8049             !(event->state & GDK_MODIFIER_MASK) &&
8050             (event->keyval == GDK_BackSpace) &&
8051             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
8052                 gtk_container_remove
8053                         (GTK_CONTAINER(headerentry->compose->header_table),
8054                          headerentry->combo);
8055                 gtk_container_remove
8056                         (GTK_CONTAINER(headerentry->compose->header_table),
8057                          headerentry->entry);
8058                 headerentry->compose->header_list =
8059                         g_slist_remove(headerentry->compose->header_list,
8060                                        headerentry);
8061                 g_free(headerentry);
8062         } else  if (event->keyval == GDK_Tab) {
8063                 if (headerentry->compose->header_last == headerentry) {
8064                         /* Override default next focus, and give it to subject_entry
8065                          * instead of notebook tabs
8066                          */
8067                         g_signal_stop_emission_by_name(G_OBJECT(entry), "key-press-event"); 
8068                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
8069                         return TRUE;
8070                 }
8071         }
8072         return FALSE;
8073 }
8074
8075 gboolean compose_headerentry_changed_cb(GtkWidget *entry,
8076                                     ComposeHeaderEntry *headerentry)
8077 {
8078         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
8079                 headerentry->compose->header_list =
8080                         g_slist_append(headerentry->compose->header_list,
8081                                        headerentry);
8082                 
8083                 compose_create_header_entry(headerentry->compose);
8084                 g_signal_handlers_disconnect_matched
8085                         (G_OBJECT(entry), G_SIGNAL_MATCH_DATA,
8086                          0, 0, NULL, NULL, headerentry);
8087                 
8088                 /* Automatically scroll down */
8089                 compose_show_first_last_header(headerentry->compose, FALSE);
8090                 
8091         }
8092         return FALSE;
8093 }
8094
8095 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
8096 {
8097         GtkAdjustment *vadj;
8098
8099         g_return_if_fail(compose);
8100         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
8101         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
8102
8103         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
8104         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
8105 }
8106
8107 static void text_inserted(GtkTextBuffer *buffer, GtkTextIter *iter,
8108                           const gchar *text, gint len, Compose *compose)
8109 {
8110         gint paste_as_quotation = GPOINTER_TO_INT(g_object_get_data
8111                                 (G_OBJECT(compose->text), "paste_as_quotation"));
8112         GtkTextMark *mark;
8113
8114         g_return_if_fail(text != NULL);
8115
8116         g_signal_handlers_block_by_func(G_OBJECT(buffer),
8117                                         G_CALLBACK(text_inserted),
8118                                         compose);
8119         if (paste_as_quotation) {
8120                 gchar *new_text;
8121                 gchar *qmark;
8122
8123                 if (len < 0)
8124                         len = strlen(text);
8125
8126                 new_text = g_strndup(text, len);
8127                 if (prefs_common.quotemark && *prefs_common.quotemark)
8128                         qmark = prefs_common.quotemark;
8129                 else
8130                         qmark = "> ";
8131
8132                 mark = gtk_text_buffer_create_mark(buffer, NULL, iter, FALSE);
8133                 gtk_text_buffer_place_cursor(buffer, iter);
8134
8135                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text, TRUE);
8136                 g_free(new_text);
8137                 g_object_set_data(G_OBJECT(compose->text), "paste_as_quotation",
8138                                   GINT_TO_POINTER(paste_as_quotation - 1));
8139                                   
8140                 gtk_text_buffer_get_iter_at_mark(buffer, iter, mark);
8141                 gtk_text_buffer_place_cursor(buffer, iter);
8142         } else {
8143                 if (strcmp(text, "\n") || automatic_break
8144                 || gtk_text_iter_starts_line(iter))
8145                         gtk_text_buffer_insert(buffer, iter, text, len);
8146                 else {
8147                         debug_print("insert nowrap \\n\n");
8148                         gtk_text_buffer_insert_with_tags_by_name(buffer, 
8149                                 iter, text, len, "no_join", NULL);
8150                 }
8151         }
8152         
8153         mark = gtk_text_buffer_create_mark(buffer, NULL, iter, FALSE);
8154         
8155         compose_beautify_paragraph(compose, iter, FALSE);
8156
8157         gtk_text_buffer_get_iter_at_mark(buffer, iter, mark);
8158         gtk_text_buffer_delete_mark(buffer, mark);
8159
8160         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
8161                                           G_CALLBACK(text_inserted),
8162                                           compose);
8163         g_signal_stop_emission_by_name(G_OBJECT(buffer), "insert-text");
8164
8165         if (prefs_common.autosave && 
8166             gtk_text_buffer_get_char_count(buffer) % prefs_common.autosave_length == 0)
8167                 compose->draft_timeout_tag = gtk_timeout_add
8168                         (500, (GtkFunction) compose_defer_auto_save_draft, compose);
8169 }
8170 static gint compose_defer_auto_save_draft(Compose *compose)
8171 {
8172         compose->draft_timeout_tag = -1;
8173         compose_draft_cb((gpointer)compose, COMPOSE_AUTO_SAVE, NULL);
8174         return FALSE;
8175 }
8176
8177 #if USE_ASPELL
8178 static void compose_check_all(Compose *compose)
8179 {
8180         if (compose->gtkaspell)
8181                 gtkaspell_check_all(compose->gtkaspell);
8182 }
8183
8184 static void compose_highlight_all(Compose *compose)
8185 {
8186         if (compose->gtkaspell)
8187                 gtkaspell_highlight_all(compose->gtkaspell);
8188 }
8189
8190 static void compose_check_backwards(Compose *compose)
8191 {
8192         if (compose->gtkaspell) 
8193                 gtkaspell_check_backwards(compose->gtkaspell);
8194         else {
8195                 GtkItemFactory *ifactory;
8196                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
8197                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
8198                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
8199         }
8200 }
8201
8202 static void compose_check_forwards_go(Compose *compose)
8203 {
8204         if (compose->gtkaspell) 
8205                 gtkaspell_check_forwards_go(compose->gtkaspell);
8206         else {
8207                 GtkItemFactory *ifactory;
8208                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
8209                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
8210                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
8211         }
8212 }
8213 #endif
8214
8215 /*!
8216  *\brief        Guess originating forward account from MsgInfo and several 
8217  *              "common preference" settings. Return NULL if no guess. 
8218  */
8219 static PrefsAccount *compose_guess_forward_account_from_msginfo(MsgInfo *msginfo)
8220 {
8221         PrefsAccount *account = NULL;
8222         
8223         g_return_val_if_fail(msginfo, NULL);
8224         g_return_val_if_fail(msginfo->folder, NULL);
8225         g_return_val_if_fail(msginfo->folder->prefs, NULL);
8226
8227         if (msginfo->folder->prefs->enable_default_account)
8228                 account = account_find_from_id(msginfo->folder->prefs->default_account);
8229                 
8230         if (!account) 
8231                 account = msginfo->folder->folder->account;
8232                 
8233         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
8234                 gchar *to;
8235                 Xstrdup_a(to, msginfo->to, return NULL);
8236                 extract_address(to);
8237                 account = account_find_from_address(to);
8238         }
8239
8240         if (!account && prefs_common.forward_account_autosel) {
8241                 gchar cc[BUFFSIZE];
8242                 if (!procheader_get_header_from_msginfo
8243                         (msginfo, cc,sizeof cc , "CC:")) { /* Found a CC header */
8244                         extract_address(cc);
8245                         account = account_find_from_address(cc);
8246                 }
8247         }
8248         
8249         return account;
8250 }
8251
8252 static gboolean compose_close(Compose *compose)
8253 {
8254         gint x, y;
8255
8256         if (!g_mutex_trylock(compose->mutex)) {
8257                 /* we have to wait for the (possibly deferred by auto-save)
8258                  * drafting to be done, before destroying the compose under
8259                  * it. */
8260                 debug_print("waiting for drafting to finish...\n");
8261                 g_timeout_add (500, (GSourceFunc) compose_close, compose);
8262                 return FALSE;
8263         }
8264         g_return_val_if_fail(compose, FALSE);
8265         gtkut_widget_get_uposition(compose->window, &x, &y);
8266         prefs_common.compose_x = x;
8267         prefs_common.compose_y = y;
8268         g_mutex_unlock(compose->mutex);
8269         compose_destroy(compose);
8270         return FALSE;
8271 }
8272
8273 /**
8274  * Add entry field for each address in list.
8275  * \param compose     E-Mail composition object.
8276  * \param listAddress List of (formatted) E-Mail addresses.
8277  */
8278 static void compose_add_field_list( Compose *compose, GList *listAddress ) {
8279         GList *node;
8280         gchar *addr;
8281         node = listAddress;
8282         while( node ) {
8283                 addr = ( gchar * ) node->data;
8284                 compose_entry_append( compose, addr, COMPOSE_TO );
8285                 node = g_list_next( node );
8286         }
8287 }
8288
8289 void compose_reply_from_messageview(MessageView *msgview, GSList *msginfo_list, 
8290                                     guint action)
8291 {
8292         gchar *body;
8293         GSList *new_msglist = NULL;
8294         MsgInfo *tmp_msginfo = NULL;
8295         gboolean originally_enc = FALSE;
8296         Compose *compose = NULL;
8297
8298         g_return_if_fail(msgview != NULL);
8299
8300         g_return_if_fail(msginfo_list != NULL);
8301
8302         if (g_slist_length(msginfo_list) == 1) {
8303                 MimeInfo *mimeinfo = messageview_get_selected_mime_part(msgview);
8304                 MsgInfo *orig_msginfo = (MsgInfo *)msginfo_list->data;
8305                 
8306                 if (mimeinfo != NULL && mimeinfo->type == MIMETYPE_MESSAGE && 
8307                     !g_ascii_strcasecmp(mimeinfo->subtype, "rfc822")) {
8308                         tmp_msginfo = procmsg_msginfo_new_from_mimeinfo(
8309                                                 orig_msginfo, mimeinfo);
8310                         if (tmp_msginfo != NULL) {
8311                                 new_msglist = g_slist_append(NULL, tmp_msginfo);
8312                                 if (procmime_msginfo_is_encrypted(orig_msginfo)) {
8313                                         originally_enc = TRUE;
8314                                 }
8315                         } 
8316                 }
8317         }
8318
8319         body = messageview_get_selection(msgview);
8320
8321         if (new_msglist) {
8322                 compose = compose_reply_mode((ComposeMode)action, new_msglist, body);
8323                 procmsg_msginfo_free(tmp_msginfo);
8324                 g_slist_free(new_msglist);
8325         } else
8326                 compose = compose_reply_mode((ComposeMode)action, msginfo_list, body);
8327
8328         if (originally_enc) {
8329                 compose_force_encryption(compose, compose->account, FALSE);
8330         }
8331
8332         g_free(body);
8333 }
8334
8335 /*
8336  * End of Source.
8337  */