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