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