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