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