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