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