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