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