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