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