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