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