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