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