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