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