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