a44ad5347eb664ec4f9230715056ee7d7cd19785
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2005 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 #ifndef PANGO_ENABLE_ENGINE
27 #  define PANGO_ENABLE_ENGINE
28 #endif
29
30 #include <glib.h>
31 #include <glib/gi18n.h>
32 #include <gdk/gdkkeysyms.h>
33 #include <gtk/gtkmain.h>
34 #include <gtk/gtkmenu.h>
35 #include <gtk/gtkmenuitem.h>
36 #include <gtk/gtkitemfactory.h>
37 #include <gtk/gtkcheckmenuitem.h>
38 #include <gtk/gtkoptionmenu.h>
39 #include <gtk/gtkwidget.h>
40 #include <gtk/gtkvpaned.h>
41 #include <gtk/gtkentry.h>
42 #include <gtk/gtkeditable.h>
43 #include <gtk/gtkwindow.h>
44 #include <gtk/gtksignal.h>
45 #include <gtk/gtkvbox.h>
46 #include <gtk/gtkcontainer.h>
47 #include <gtk/gtkhandlebox.h>
48 #include <gtk/gtktoolbar.h>
49 #include <gtk/gtktable.h>
50 #include <gtk/gtkhbox.h>
51 #include <gtk/gtklabel.h>
52 #include <gtk/gtkscrolledwindow.h>
53 #include <gtk/gtktreeview.h>
54 #include <gtk/gtkliststore.h>
55 #include <gtk/gtktreeselection.h>
56 #include <gtk/gtktreemodel.h>
57
58 #include <gtk/gtkdnd.h>
59 #include <gtk/gtkclipboard.h>
60 #include <pango/pango-break.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <ctype.h>
65 #include <sys/types.h>
66 #include <sys/stat.h>
67 #include <unistd.h>
68 #include <time.h>
69 /* #include <sys/utsname.h> */
70 #include <stdlib.h>
71 #include <sys/wait.h>
72 #include <signal.h>
73 #include <errno.h>
74 #include <libgen.h>
75
76 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
77 #  include <wchar.h>
78 #  include <wctype.h>
79 #endif
80
81 #include "main.h"
82 #include "mainwindow.h"
83 #include "compose.h"
84 #include "addressbook.h"
85 #include "folderview.h"
86 #include "procmsg.h"
87 #include "menu.h"
88 #include "stock_pixmap.h"
89 #include "send_message.h"
90 #include "imap.h"
91 #include "news.h"
92 #include "customheader.h"
93 #include "prefs_common.h"
94 #include "prefs_account.h"
95 #include "action.h"
96 #include "account.h"
97 #include "filesel.h"
98 #include "procheader.h"
99 #include "procmime.h"
100 #include "statusbar.h"
101 #include "about.h"
102 #include "base64.h"
103 #include "quoted-printable.h"
104 #include "codeconv.h"
105 #include "utils.h"
106 #include "gtkutils.h"
107 #include "socket.h"
108 #include "alertpanel.h"
109 #include "manage_window.h"
110 #include "gtkshruler.h"
111 #include "folder.h"
112 #include "addr_compl.h"
113 #include "quote_fmt.h"
114 #include "template.h"
115 #include "undo.h"
116 #include "foldersel.h"
117 #include "toolbar.h"
118
119 enum
120 {
121         COL_MIMETYPE = 0,
122         COL_SIZE     = 1,
123         COL_NAME     = 2,
124         COL_DATA     = 3,
125         COL_AUTODATA = 4,
126         N_COL_COLUMNS
127 };
128
129 #define N_ATTACH_COLS   (N_COL_COLUMNS)
130
131 typedef enum
132 {
133         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
134         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
135         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
136         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
137         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
138         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
139         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
140         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
141         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
142         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
143         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
144         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
145         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
146         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
147         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END
148 } ComposeCallAdvancedAction;
149
150 typedef enum
151 {
152         PRIORITY_HIGHEST = 1,
153         PRIORITY_HIGH,
154         PRIORITY_NORMAL,
155         PRIORITY_LOW,
156         PRIORITY_LOWEST
157 } PriorityLevel;
158
159 typedef enum
160 {
161         COMPOSE_INSERT_SUCCESS,
162         COMPOSE_INSERT_READ_ERROR,
163         COMPOSE_INSERT_INVALID_CHARACTER,
164         COMPOSE_INSERT_NO_FILE
165 } ComposeInsertResult;
166
167 typedef enum
168 {
169         COMPOSE_QUIT_EDITING,
170         COMPOSE_KEEP_EDITING,
171         COMPOSE_AUTO_SAVE
172 } ComposeDraftAction;
173
174 typedef enum
175 {
176         COMPOSE_WRITE_FOR_SEND,
177         COMPOSE_WRITE_FOR_STORE
178 } ComposeWriteType;
179
180 #define B64_LINE_SIZE           57
181 #define B64_BUFFSIZE            77
182
183 #define MAX_REFERENCES_LEN      999
184
185 static GdkColor quote_color = {0, 0, 0, 0xbfff};
186
187 static GList *compose_list = NULL;
188
189 Compose *compose_generic_new                    (PrefsAccount   *account,
190                                                  const gchar    *to,
191                                                  FolderItem     *item,
192                                                  GPtrArray      *attach_files,
193                                                  GList          *listAddress );
194
195 static Compose *compose_create                  (PrefsAccount   *account,
196                                                  ComposeMode     mode);
197
198 static GtkWidget *compose_account_option_menu_create
199                                                 (Compose        *compose);
200 static void compose_set_template_menu           (Compose        *compose);
201 static void compose_template_apply              (Compose        *compose,
202                                                  Template       *tmpl,
203                                                  gboolean        replace);
204 static void compose_destroy                     (Compose        *compose);
205
206 static void compose_entries_set                 (Compose        *compose,
207                                                  const gchar    *mailto);
208 static gint compose_parse_header                (Compose        *compose,
209                                                  MsgInfo        *msginfo);
210 static gchar *compose_parse_references          (const gchar    *ref,
211                                                  const gchar    *msgid);
212
213 static gchar *compose_quote_fmt                 (Compose        *compose,
214                                                  MsgInfo        *msginfo,
215                                                  const gchar    *fmt,
216                                                  const gchar    *qmark,
217                                                  const gchar    *body);
218
219 static void compose_reply_set_entry             (Compose        *compose,
220                                                  MsgInfo        *msginfo,
221                                                  gboolean        to_all,
222                                                  gboolean        to_ml,
223                                                  gboolean        to_sender,
224                                                  gboolean
225                                                  followup_and_reply_to);
226 static void compose_reedit_set_entry            (Compose        *compose,
227                                                  MsgInfo        *msginfo);
228
229 static void compose_insert_sig                  (Compose        *compose,
230                                                  gboolean        replace);
231 static gchar *compose_get_signature_str         (Compose        *compose);
232 static ComposeInsertResult compose_insert_file  (Compose        *compose,
233                                                  const gchar    *file);
234
235 static void compose_attach_append               (Compose        *compose,
236                                                  const gchar    *file,
237                                                  const gchar    *type,
238                                                  const gchar    *content_type);
239 static void compose_attach_parts                (Compose        *compose,
240                                                  MsgInfo        *msginfo);
241
242 static void compose_wrap_paragraph              (Compose        *compose,
243                                                  GtkTextIter    *par_iter);
244 static void compose_wrap_all                    (Compose        *compose);
245 static void compose_wrap_all_full               (Compose        *compose,
246                                                  gboolean        autowrap);
247
248 static void compose_set_title                   (Compose        *compose);
249 static void compose_select_account              (Compose        *compose,
250                                                  PrefsAccount   *account,
251                                                  gboolean        init);
252
253 static PrefsAccount *compose_current_mail_account(void);
254 /* static gint compose_send                     (Compose        *compose); */
255 static gboolean compose_check_for_valid_recipient
256                                                 (Compose        *compose);
257 static gboolean compose_check_entries           (Compose        *compose,
258                                                  gboolean       check_subject);
259 static gint compose_write_to_file               (Compose        *compose,
260                                                  FILE           *fp,
261                                                  gint            action);
262 static gint compose_write_body_to_file          (Compose        *compose,
263                                                  const gchar    *file);
264 static gint compose_remove_reedit_target        (Compose        *compose);
265 void compose_remove_draft                       (Compose        *compose);
266 static gint compose_queue                       (Compose        *compose,
267                                                  gint           *msgnum,
268                                                  FolderItem     **item);
269 static gint compose_queue_sub                   (Compose        *compose,
270                                                  gint           *msgnum,
271                                                  FolderItem     **item,
272                                                  gboolean       check_subject);
273 static void compose_add_attachments             (Compose        *compose,
274                                                  MimeInfo       *parent);
275 static gchar *compose_get_header                (Compose        *compose);
276
277 static void compose_convert_header              (gchar          *dest,
278                                                  gint            len,
279                                                  gchar          *src,
280                                                  gint            header_len,
281                                                  gboolean        addr_field);
282
283 static void compose_attach_info_free            (AttachInfo     *ainfo);
284 static void compose_attach_remove_selected      (Compose        *compose);
285
286 static void compose_attach_property             (Compose        *compose);
287 static void compose_attach_property_create      (gboolean       *cancelled);
288 static void attach_property_ok                  (GtkWidget      *widget,
289                                                  gboolean       *cancelled);
290 static void attach_property_cancel              (GtkWidget      *widget,
291                                                  gboolean       *cancelled);
292 static gint attach_property_delete_event        (GtkWidget      *widget,
293                                                  GdkEventAny    *event,
294                                                  gboolean       *cancelled);
295 static gboolean attach_property_key_pressed     (GtkWidget      *widget,
296                                                  GdkEventKey    *event,
297                                                  gboolean       *cancelled);
298
299 static void compose_exec_ext_editor             (Compose           *compose);
300 static gint compose_exec_ext_editor_real        (const gchar       *file);
301 static gboolean compose_ext_editor_kill         (Compose           *compose);
302 static void compose_input_cb                    (gpointer           data,
303                                                  gint               source,
304                                                  GdkInputCondition  condition);
305 static void compose_set_ext_editor_sensitive    (Compose           *compose,
306                                                  gboolean           sensitive);
307
308 static void compose_undo_state_changed          (UndoMain       *undostruct,
309                                                  gint            undo_state,
310                                                  gint            redo_state,
311                                                  gpointer        data);
312
313 static void compose_create_header_entry (Compose *compose);
314 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
315 static void compose_update_priority_menu_item(Compose * compose);
316
317 static void compose_add_field_list      ( Compose *compose,
318                                           GList *listAddress );
319
320 /* callback functions */
321
322 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
323                                          GtkAllocation  *allocation,
324                                          GtkSHRuler     *shruler);
325 static void account_activated           (GtkMenuItem    *menuitem,
326                                          gpointer        data);
327 static void attach_selected             (GtkTreeView    *tree_view, 
328                                          GtkTreePath    *tree_path,
329                                          GtkTreeViewColumn *column, 
330                                          Compose *compose);
331 static gboolean attach_button_pressed   (GtkWidget      *widget,
332                                          GdkEventButton *event,
333                                          gpointer        data);
334 static gboolean attach_key_pressed      (GtkWidget      *widget,
335                                          GdkEventKey    *event,
336                                          gpointer        data);
337
338 static void compose_send_cb             (gpointer        data,
339                                          guint           action,
340                                          GtkWidget      *widget);
341 static void compose_send_later_cb       (gpointer        data,
342                                          guint           action,
343                                          GtkWidget      *widget);
344
345 static void compose_draft_cb            (gpointer        data,
346                                          guint           action,
347                                          GtkWidget      *widget);
348
349 static void compose_attach_cb           (gpointer        data,
350                                          guint           action,
351                                          GtkWidget      *widget);
352 static void compose_insert_file_cb      (gpointer        data,
353                                          guint           action,
354                                          GtkWidget      *widget);
355 static void compose_insert_sig_cb       (gpointer        data,
356                                          guint           action,
357                                          GtkWidget      *widget);
358
359 static void compose_close_cb            (gpointer        data,
360                                          guint           action,
361                                          GtkWidget      *widget);
362
363 static void compose_address_cb          (gpointer        data,
364                                          guint           action,
365                                          GtkWidget      *widget);
366 static void compose_template_activate_cb(GtkWidget      *widget,
367                                          gpointer        data);
368
369 static void compose_ext_editor_cb       (gpointer        data,
370                                          guint           action,
371                                          GtkWidget      *widget);
372
373 static gint compose_delete_cb           (GtkWidget      *widget,
374                                          GdkEventAny    *event,
375                                          gpointer        data);
376 static void compose_destroy_cb          (GtkWidget      *widget,
377                                          Compose        *compose);
378
379 static void compose_undo_cb             (Compose        *compose);
380 static void compose_redo_cb             (Compose        *compose);
381 static void compose_cut_cb              (Compose        *compose);
382 static void compose_copy_cb             (Compose        *compose);
383 static void compose_paste_cb            (Compose        *compose);
384 static void compose_paste_as_quote_cb   (Compose        *compose);
385 static void compose_allsel_cb           (Compose        *compose);
386
387 static void compose_advanced_action_cb  (Compose                   *compose,
388                                          ComposeCallAdvancedAction  action);
389
390 static void compose_grab_focus_cb       (GtkWidget      *widget,
391                                          Compose        *compose);
392
393 static void compose_changed_cb          (GtkTextBuffer  *textbuf,
394                                          Compose        *compose);
395
396 static void compose_wrap_cb             (gpointer        data,
397                                          guint           action,
398                                          GtkWidget      *widget);
399 static void compose_toggle_autowrap_cb  (gpointer        data,
400                                          guint           action,
401                                          GtkWidget      *widget);
402
403 #if 0
404 static void compose_toggle_to_cb        (gpointer        data,
405                                          guint           action,
406                                          GtkWidget      *widget);
407 static void compose_toggle_cc_cb        (gpointer        data,
408                                          guint           action,
409                                          GtkWidget      *widget);
410 static void compose_toggle_bcc_cb       (gpointer        data,
411                                          guint           action,
412                                          GtkWidget      *widget);
413 static void compose_toggle_replyto_cb   (gpointer        data,
414                                          guint           action,
415                                          GtkWidget      *widget);
416 static void compose_toggle_followupto_cb(gpointer        data,
417                                          guint           action,
418                                          GtkWidget      *widget);
419 static void compose_toggle_attach_cb    (gpointer        data,
420                                          guint           action,
421                                          GtkWidget      *widget);
422 #endif
423 static void compose_toggle_ruler_cb     (gpointer        data,
424                                          guint           action,
425                                          GtkWidget      *widget);
426 static void compose_toggle_sign_cb      (gpointer        data,
427                                          guint           action,
428                                          GtkWidget      *widget);
429 static void compose_toggle_encrypt_cb   (gpointer        data,
430                                          guint           action,
431                                          GtkWidget      *widget);
432 static void compose_set_privacy_system_cb(GtkWidget      *widget,
433                                           gpointer        data);
434 static void compose_update_privacy_system_menu_item(Compose * compose);
435 static void activate_privacy_system     (Compose *compose, 
436                                          PrefsAccount *account);
437 static void compose_use_signing(Compose *compose, gboolean use_signing);
438 static void compose_use_encryption(Compose *compose, gboolean use_encryption);
439 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
440                                              GtkWidget *widget);
441 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
442                                              GtkWidget *widget);
443 static void compose_set_priority_cb     (gpointer        data,
444                                          guint           action,
445                                          GtkWidget      *widget);
446
447 static void compose_attach_drag_received_cb (GtkWidget          *widget,
448                                              GdkDragContext     *drag_context,
449                                              gint                x,
450                                              gint                y,
451                                              GtkSelectionData   *data,
452                                              guint               info,
453                                              guint               time,
454                                              gpointer            user_data);
455 static void compose_insert_drag_received_cb (GtkWidget          *widget,
456                                              GdkDragContext     *drag_context,
457                                              gint                x,
458                                              gint                y,
459                                              GtkSelectionData   *data,
460                                              guint               info,
461                                              guint               time,
462                                              gpointer            user_data);
463 static void compose_header_drag_received_cb (GtkWidget          *widget,
464                                              GdkDragContext     *drag_context,
465                                              gint                x,
466                                              gint                y,
467                                              GtkSelectionData   *data,
468                                              guint               info,
469                                              guint               time,
470                                              gpointer            user_data);
471
472 static gboolean compose_drag_drop           (GtkWidget *widget,
473                                              GdkDragContext *drag_context,
474                                              gint x, gint y,
475                                              guint time, gpointer user_data);
476 #if 0
477 static void to_activated                (GtkWidget      *widget,
478                                          Compose        *compose);
479 static void newsgroups_activated        (GtkWidget      *widget,
480                                          Compose        *compose);
481 static void cc_activated                (GtkWidget      *widget,
482                                          Compose        *compose);
483 static void bcc_activated               (GtkWidget      *widget,
484                                          Compose        *compose);
485 static void replyto_activated           (GtkWidget      *widget,
486                                          Compose        *compose);
487 static void followupto_activated        (GtkWidget      *widget,
488                                          Compose        *compose);
489 static void subject_activated           (GtkWidget      *widget,
490                                          Compose        *compose);
491 #endif
492
493 static void text_inserted               (GtkTextBuffer  *buffer,
494                                          GtkTextIter    *iter,
495                                          const gchar    *text,
496                                          gint            len,
497                                          Compose        *compose);
498 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
499                                   gboolean to_all, gboolean to_ml,
500                                   gboolean to_sender,
501                                   gboolean followup_and_reply_to,
502                                   const gchar *body);
503
504 gboolean compose_headerentry_changed_cb    (GtkWidget          *entry,
505                                             ComposeHeaderEntry *headerentry);
506 gboolean compose_headerentry_key_press_event_cb(GtkWidget              *entry,
507                                             GdkEventKey        *event,
508                                             ComposeHeaderEntry *headerentry);
509
510 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
511
512 static void compose_allow_user_actions (Compose *compose, gboolean allow);
513
514 #if USE_ASPELL
515 static void compose_check_all              (Compose *compose);
516 static void compose_highlight_all          (Compose *compose);
517 static void compose_check_backwards        (Compose *compose);
518 static void compose_check_forwards_go      (Compose *compose);
519 #endif
520
521 static gint compose_defer_auto_save_draft       (Compose        *compose);
522 static PrefsAccount *compose_guess_forward_account_from_msginfo (MsgInfo *msginfo);
523
524 static void compose_close       (Compose *compose);
525
526 static GtkItemFactoryEntry compose_popup_entries[] =
527 {
528         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
529         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
530         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
531         {N_("/_Properties..."), NULL, compose_attach_property, 0, NULL}
532 };
533
534 static GtkItemFactoryEntry compose_entries[] =
535 {
536         {N_("/_Message"),                               NULL, NULL, 0, "<Branch>"},
537         {N_("/_Message/_Send"),         "<control>Return",
538                                         compose_send_cb, 0, NULL},
539         {N_("/_Message/Send _later"),   "<shift><control>S",
540                                         compose_send_later_cb,  0, NULL},
541         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
542         {N_("/_Message/_Attach file"),          "<control>M", compose_attach_cb,      0, NULL},
543         {N_("/_Message/_Insert file"),          "<control>I", compose_insert_file_cb, 0, NULL},
544         {N_("/_Message/Insert si_gnature"),     "<control>G", compose_insert_sig_cb,  0, NULL},
545         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
546         {N_("/_Message/_Save"),
547                                                 "<control>S", compose_draft_cb, COMPOSE_KEEP_EDITING, NULL},
548         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
549         {N_("/_Message/_Close"),                        "<control>W", compose_close_cb, 0, NULL},
550
551         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
552         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
553         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
554         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
555         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
556         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
557         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
558         {N_("/_Edit/Paste as _quotation"),
559                                         NULL, compose_paste_as_quote_cb, 0, NULL},
560         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
561         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
562         {N_("/_Edit/A_dvanced/Move a character backward"),
563                                         "<control>B",
564                                         compose_advanced_action_cb,
565                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
566                                         NULL},
567         {N_("/_Edit/A_dvanced/Move a character forward"),
568                                         "<control>F",
569                                         compose_advanced_action_cb,
570                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
571                                         NULL},
572         {N_("/_Edit/A_dvanced/Move a word backward"),
573                                         NULL, /* "<alt>B" */
574                                         compose_advanced_action_cb,
575                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
576                                         NULL},
577         {N_("/_Edit/A_dvanced/Move a word forward"),
578                                         NULL, /* "<alt>F" */
579                                         compose_advanced_action_cb,
580                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
581                                         NULL},
582         {N_("/_Edit/A_dvanced/Move to beginning of line"),
583                                         NULL, /* "<control>A" */
584                                         compose_advanced_action_cb,
585                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
586                                         NULL},
587         {N_("/_Edit/A_dvanced/Move to end of line"),
588                                         "<control>E",
589                                         compose_advanced_action_cb,
590                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
591                                         NULL},
592         {N_("/_Edit/A_dvanced/Move to previous line"),
593                                         "<control>P",
594                                         compose_advanced_action_cb,
595                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
596                                         NULL},
597         {N_("/_Edit/A_dvanced/Move to next line"),
598                                         "<control>N",
599                                         compose_advanced_action_cb,
600                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
601                                         NULL},
602         {N_("/_Edit/A_dvanced/Delete a character backward"),
603                                         "<control>H",
604                                         compose_advanced_action_cb,
605                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
606                                         NULL},
607         {N_("/_Edit/A_dvanced/Delete a character forward"),
608                                         "<control>D",
609                                         compose_advanced_action_cb,
610                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
611                                         NULL},
612         {N_("/_Edit/A_dvanced/Delete a word backward"),
613                                         NULL, /* "<control>W" */
614                                         compose_advanced_action_cb,
615                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
616                                         NULL},
617         {N_("/_Edit/A_dvanced/Delete a word forward"),
618                                         NULL, /* "<alt>D", */
619                                         compose_advanced_action_cb,
620                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
621                                         NULL},
622         {N_("/_Edit/A_dvanced/Delete line"),
623                                         "<control>U",
624                                         compose_advanced_action_cb,
625                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
626                                         NULL},
627         {N_("/_Edit/A_dvanced/Delete entire line"),
628                                         NULL,
629                                         compose_advanced_action_cb,
630                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
631                                         NULL},
632         {N_("/_Edit/A_dvanced/Delete to end of line"),
633                                         "<control>K",
634                                         compose_advanced_action_cb,
635                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END,
636                                         NULL},
637         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
638         {N_("/_Edit/_Wrap current paragraph"),
639                                         "<control>L", compose_wrap_cb, 0, NULL},
640         {N_("/_Edit/Wrap all long _lines"),
641                                         "<control><alt>L", compose_wrap_cb, 1, NULL},
642         {N_("/_Edit/Aut_o wrapping"),   "<shift><control>L", compose_toggle_autowrap_cb, 0, "<ToggleItem>"},
643         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
644         {N_("/_Edit/Edit with e_xternal editor"),
645                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
646 #if USE_ASPELL
647         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
648         {N_("/_Spelling/_Check all or check selection"),
649                                         NULL, compose_check_all, 0, NULL},
650         {N_("/_Spelling/_Highlight all misspelled words"),
651                                         NULL, compose_highlight_all, 0, NULL},
652         {N_("/_Spelling/Check _backwards misspelled word"),
653                                         NULL, compose_check_backwards , 0, NULL},
654         {N_("/_Spelling/_Forward to next misspelled word"),
655                                         NULL, compose_check_forwards_go, 0, NULL},
656         {N_("/_Spelling/---"),          NULL, NULL, 0, "<Separator>"},
657         {N_("/_Spelling/_Spelling Configuration"),
658                                         NULL, NULL, 0, "<Branch>"},
659 #endif
660         {N_("/_Options"),               NULL, NULL, 0, "<Branch>"},
661         {N_("/_Options/Privacy System"),                NULL, NULL,   0, "<Branch>"},
662         {N_("/_Options/Privacy System/None"),   NULL, NULL,   0, "<RadioItem>"},
663         {N_("/_Options/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
664         {N_("/_Options/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
665         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
666         {N_("/_Options/_Priority"),     NULL,           NULL,   0, "<Branch>"},
667         {N_("/_Options/Priority/_Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
668         {N_("/_Options/Priority/Hi_gh"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Options/Priority/Highest"},
669         {N_("/_Options/Priority/_Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Options/Priority/Highest"},
670         {N_("/_Options/Priority/Lo_w"),    NULL, compose_set_priority_cb, PRIORITY_LOW, "/Options/Priority/Highest"},
671         {N_("/_Options/Priority/_Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Options/Priority/Highest"},
672         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
673         {N_("/_Options/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
674         {N_("/_Options/Remo_ve references"),    NULL, compose_toggle_remove_refs_cb, 0, "<ToggleItem>"},
675         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
676         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
677         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
678         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
679         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
680         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
681         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
682 };
683
684 static GtkTargetEntry compose_mime_types[] =
685 {
686         {"text/uri-list", 0, 0},
687         {"text/plain", 0, 0},
688         {"STRING", 0, 0}
689 };
690
691 static gboolean compose_put_existing_to_front(MsgInfo *info)
692 {
693         GList *compose_list = compose_get_compose_list();
694         GList *elem = NULL;
695         
696         if (compose_list) {
697                 for (elem = compose_list; elem != NULL && elem->data != NULL; 
698                      elem = elem->next) {
699                         Compose *c = (Compose*)elem->data;
700
701                         if (!c->targetinfo || !c->targetinfo->msgid ||
702                             !info->msgid)
703                                 continue;
704
705                         if (!strcmp(c->targetinfo->msgid, info->msgid)) {
706                                 gtkut_window_popup(c->window);
707                                 return TRUE;
708                         }
709                 }
710         }
711         return FALSE;
712 }
713
714 Compose *compose_new(PrefsAccount *account, const gchar *mailto,
715                      GPtrArray *attach_files)
716 {
717         return compose_generic_new(account, mailto, NULL, attach_files, NULL);
718 }
719
720 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
721 {
722         return compose_generic_new(account, NULL, item, NULL, NULL);
723 }
724
725 Compose *compose_new_with_list( PrefsAccount *account, GList *listAddress )
726 {
727         return compose_generic_new( account, NULL, NULL, NULL, listAddress );
728 }
729
730 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item,
731                              GPtrArray *attach_files, GList *listAddress )
732 {
733         Compose *compose;
734         GtkTextView *textview;
735         GtkTextBuffer *textbuf;
736         GtkTextIter iter;
737         GtkItemFactory *ifactory;
738
739         if (item && item->prefs && item->prefs->enable_default_account)
740                 account = account_find_from_id(item->prefs->default_account);
741
742         if (!account) account = cur_account;
743         g_return_val_if_fail(account != NULL, NULL);
744
745         compose = compose_create(account, COMPOSE_NEW);
746         ifactory = gtk_item_factory_from_widget(compose->menubar);
747
748         compose->replyinfo = NULL;
749         compose->fwdinfo   = NULL;
750
751         textview = GTK_TEXT_VIEW(compose->text);
752         textbuf = gtk_text_view_get_buffer(textview);
753
754         undo_block(compose->undostruct);
755 #ifdef USE_ASPELL
756         if (item && item->prefs && item->prefs->enable_default_dictionary &&
757             compose->gtkaspell) 
758                 gtkaspell_change_dict(compose->gtkaspell, 
759                     item->prefs->default_dictionary);
760 #endif
761
762         if (account->auto_sig)
763                 compose_insert_sig(compose, FALSE);
764         gtk_text_buffer_get_start_iter(textbuf, &iter);
765         gtk_text_buffer_place_cursor(textbuf, &iter);
766
767         if (account->protocol != A_NNTP) {
768                 if (mailto && *mailto != '\0') {
769                         compose_entries_set(compose, mailto);
770
771                 } else if (item && item->prefs->enable_default_to) {
772                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
773                         compose_entry_mark_default_to(compose, item->prefs->default_to);
774                 }
775                 if (item && item->ret_rcpt) {
776                         menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
777                 }
778         } else {
779                 if (mailto) {
780                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
781                 }
782                 /*
783                  * CLAWS: just don't allow return receipt request, even if the user
784                  * may want to send an email. simple but foolproof.
785                  */
786                 menu_set_sensitive(ifactory, "/Options/Request Return Receipt", FALSE); 
787         }
788         compose_add_field_list( compose, listAddress );
789
790         if (attach_files) {
791                 gint i;
792                 gchar *file;
793
794                 for (i = 0; i < attach_files->len; i++) {
795                         file = g_ptr_array_index(attach_files, i);
796                         compose_attach_append(compose, file, file, NULL);
797                 }
798         }
799
800         compose_show_first_last_header(compose, TRUE);
801
802         /* Set save folder */
803         if (item && item->prefs && item->prefs->save_copy_to_folder) {
804                 gchar *folderidentifier;
805
806                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
807                 folderidentifier = folder_item_get_identifier(item);
808                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
809                 g_free(folderidentifier);
810         }
811         
812         gtk_widget_grab_focus(compose->header_last->entry);
813
814         undo_unblock(compose->undostruct);
815
816         if (prefs_common.auto_exteditor)
817                 compose_exec_ext_editor(compose);
818
819         return compose;
820 }
821
822 /*
823 Compose *compose_new_followup_and_replyto(PrefsAccount *account,
824                                            const gchar *followupto, gchar * to)
825 {
826         Compose *compose;
827
828         if (!account) account = cur_account;
829         g_return_val_if_fail(account != NULL, NULL);
830         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
831
832         compose = compose_create(account, COMPOSE_NEW);
833
834         if (prefs_common.auto_sig)
835                 compose_insert_sig(compose);
836         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
837         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
838
839         compose_entry_append(compose, to, COMPOSE_TO);
840         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
841         gtk_widget_grab_focus(compose->subject_entry);
842
843         return compose;
844 }
845 */
846
847 void compose_reply_mode(ComposeMode mode, GSList *msginfo_list, gchar *body)
848 {
849         MsgInfo *msginfo;
850         guint list_len;
851
852         g_return_if_fail(msginfo_list != NULL);
853
854         msginfo = (MsgInfo*)g_slist_nth_data(msginfo_list, 0);
855         g_return_if_fail(msginfo != NULL);
856
857         list_len = g_slist_length(msginfo_list);
858
859         switch (mode) {
860         case COMPOSE_REPLY:
861                 compose_reply(msginfo, prefs_common.reply_with_quote,
862                               FALSE, prefs_common.default_reply_list, FALSE, body);
863                 break;
864         case COMPOSE_REPLY_WITH_QUOTE:
865                 compose_reply(msginfo, TRUE, FALSE, prefs_common.default_reply_list, FALSE, body);
866                 break;
867         case COMPOSE_REPLY_WITHOUT_QUOTE:
868                 compose_reply(msginfo, FALSE, FALSE, prefs_common.default_reply_list, FALSE, NULL);
869                 break;
870         case COMPOSE_REPLY_TO_SENDER:
871                 compose_reply(msginfo, prefs_common.reply_with_quote,
872                               FALSE, FALSE, TRUE, body);
873                 break;
874         case COMPOSE_FOLLOWUP_AND_REPLY_TO:
875                 compose_followup_and_reply_to(msginfo,
876                                               prefs_common.reply_with_quote,
877                                               FALSE, FALSE, body);
878                 break;
879         case COMPOSE_REPLY_TO_SENDER_WITH_QUOTE:
880                 compose_reply(msginfo, TRUE, FALSE, FALSE, TRUE, body);
881                 break;
882         case COMPOSE_REPLY_TO_SENDER_WITHOUT_QUOTE:
883                 compose_reply(msginfo, FALSE, FALSE, FALSE, TRUE, NULL);
884                 break;
885         case COMPOSE_REPLY_TO_ALL:
886                 compose_reply(msginfo, prefs_common.reply_with_quote,
887                               TRUE, FALSE, FALSE, body);
888                 break;
889         case COMPOSE_REPLY_TO_ALL_WITH_QUOTE:
890                 compose_reply(msginfo, TRUE, TRUE, FALSE, FALSE, body);
891                 break;
892         case COMPOSE_REPLY_TO_ALL_WITHOUT_QUOTE:
893                 compose_reply(msginfo, FALSE, TRUE, FALSE, FALSE, NULL);
894                 break;
895         case COMPOSE_REPLY_TO_LIST:
896                 compose_reply(msginfo, prefs_common.reply_with_quote,
897                               FALSE, TRUE, FALSE, body);
898                 break;
899         case COMPOSE_REPLY_TO_LIST_WITH_QUOTE:
900                 compose_reply(msginfo, TRUE, FALSE, TRUE, FALSE, body);
901                 break;
902         case COMPOSE_REPLY_TO_LIST_WITHOUT_QUOTE:
903                 compose_reply(msginfo, FALSE, FALSE, TRUE, FALSE, NULL);
904                 break;
905         case COMPOSE_FORWARD:
906                 if (prefs_common.forward_as_attachment) {
907                         compose_reply_mode(COMPOSE_FORWARD_AS_ATTACH, msginfo_list, body);
908                         return;
909                 } else {
910                         compose_reply_mode(COMPOSE_FORWARD_INLINE, msginfo_list, body);
911                         return;
912                 }
913                 break;
914         case COMPOSE_FORWARD_INLINE:
915                 /* check if we reply to more than one Message */
916                 if (list_len == 1) {
917                         compose_forward(NULL, msginfo, FALSE, body, FALSE);
918                         break;
919                 } 
920                 /* more messages FALL THROUGH */
921         case COMPOSE_FORWARD_AS_ATTACH:
922                 compose_forward_multiple(NULL, msginfo_list);
923                 break;
924         case COMPOSE_REDIRECT:
925                 compose_redirect(NULL, msginfo);
926                 break;
927         default:
928                 g_warning("compose_reply(): invalid Compose Mode: %d\n", mode);
929         }
930 }
931
932 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
933                    gboolean to_ml, gboolean to_sender, 
934                    const gchar *body)
935 {
936         compose_generic_reply(msginfo, quote, to_all, to_ml, 
937                               to_sender, FALSE, body);
938 }
939
940 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
941                                    gboolean to_all,
942                                    gboolean to_sender,
943                                    const gchar *body)
944 {
945         compose_generic_reply(msginfo, quote, to_all, FALSE, 
946                               to_sender, TRUE, body);
947 }
948
949 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
950                                   gboolean to_all, gboolean to_ml,
951                                   gboolean to_sender,
952                                   gboolean followup_and_reply_to,
953                                   const gchar *body)
954 {
955         GtkItemFactory *ifactory;
956         Compose *compose;
957         PrefsAccount *account = NULL;
958         PrefsAccount *reply_account;
959         GtkTextView *textview;
960         GtkTextBuffer *textbuf;
961         GtkTextIter iter;
962         int cursor_pos;
963
964         g_return_if_fail(msginfo != NULL);
965         g_return_if_fail(msginfo->folder != NULL);
966
967         account = account_get_reply_account(msginfo, prefs_common.reply_account_autosel);
968         
969         g_return_if_fail(account != NULL);
970
971         if (to_sender && account->protocol == A_NNTP &&
972             !followup_and_reply_to) {
973                 reply_account =
974                         account_find_from_address(account->address);
975                 if (!reply_account)
976                         reply_account = compose_current_mail_account();
977                 if (!reply_account)
978                         return;
979         } else
980                 reply_account = account;
981
982         compose = compose_create(account, COMPOSE_REPLY);
983         ifactory = gtk_item_factory_from_widget(compose->menubar);
984
985         menu_set_active(ifactory, "/Options/Remove references", FALSE);
986         menu_set_sensitive(ifactory, "/Options/Remove references", TRUE);
987
988         compose->replyinfo = procmsg_msginfo_get_full_info(msginfo);
989         if (!compose->replyinfo)
990                 compose->replyinfo = procmsg_msginfo_copy(msginfo);
991
992         if (msginfo->folder && msginfo->folder->ret_rcpt)
993                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
994
995         /* Set save folder */
996         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
997                 gchar *folderidentifier;
998
999                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1000                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1001                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1002                 g_free(folderidentifier);
1003         }
1004
1005         if (compose_parse_header(compose, msginfo) < 0) return;
1006         compose_reply_set_entry(compose, msginfo, to_all, to_ml, 
1007                                 to_sender, followup_and_reply_to);
1008         compose_show_first_last_header(compose, TRUE);
1009
1010         textview = (GTK_TEXT_VIEW(compose->text));
1011         textbuf = gtk_text_view_get_buffer(textview);
1012         
1013         undo_block(compose->undostruct);
1014 #ifdef USE_ASPELL
1015         if (msginfo->folder && msginfo->folder->prefs && 
1016             msginfo->folder->prefs && 
1017             msginfo->folder->prefs->enable_default_dictionary &&
1018             compose->gtkaspell)
1019                 gtkaspell_change_dict(compose->gtkaspell, 
1020                     msginfo->folder->prefs->default_dictionary);
1021 #endif
1022
1023         if (quote) {
1024                 gchar *qmark;
1025
1026                 if (prefs_common.quotemark && *prefs_common.quotemark)
1027                         qmark = prefs_common.quotemark;
1028                 else
1029                         qmark = "> ";
1030
1031                 compose_quote_fmt(compose, compose->replyinfo,
1032                                   prefs_common.quotefmt,
1033                                   qmark, body);
1034         }
1035
1036         if (account->auto_sig)
1037                 compose_insert_sig(compose, FALSE);
1038
1039         cursor_pos = quote_fmt_get_cursor_pos();
1040         gtk_text_buffer_get_start_iter(textbuf, &iter);
1041         gtk_text_buffer_get_iter_at_offset(textbuf, &iter, cursor_pos);
1042         gtk_text_buffer_place_cursor(textbuf, &iter);
1043         
1044         if (quote && prefs_common.linewrap_quote)
1045                 compose_wrap_all(compose);
1046
1047         gtk_widget_grab_focus(compose->text);
1048
1049         undo_unblock(compose->undostruct);
1050
1051         if (prefs_common.auto_exteditor)
1052                 compose_exec_ext_editor(compose);
1053 }
1054
1055 #define INSERT_FW_HEADER(var, hdr) \
1056 if (msginfo->var && *msginfo->var) { \
1057         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1058         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1059         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1060 }
1061
1062 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1063                          gboolean as_attach, const gchar *body,
1064                          gboolean no_extedit)
1065 {
1066         Compose *compose;
1067         GtkTextView *textview;
1068         GtkTextBuffer *textbuf;
1069         GtkTextIter iter;
1070
1071         g_return_val_if_fail(msginfo != NULL, NULL);
1072         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1073
1074         if (!account && 
1075             !(account = compose_guess_forward_account_from_msginfo
1076                                 (msginfo)))
1077                 account = cur_account;
1078
1079         compose = compose_create(account, COMPOSE_FORWARD);
1080
1081         compose->fwdinfo = procmsg_msginfo_get_full_info(msginfo);
1082         if (!compose->fwdinfo)
1083                 compose->fwdinfo = procmsg_msginfo_copy(msginfo);
1084
1085         if (msginfo->subject && *msginfo->subject) {
1086                 gchar *buf, *buf2, *p;
1087
1088                 buf = p = g_strdup(msginfo->subject);
1089                 p += subject_get_prefix_length(p);
1090                 memmove(buf, p, strlen(p) + 1);
1091
1092                 buf2 = g_strdup_printf("Fw: %s", buf);
1093                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1094                 
1095                 g_free(buf);
1096                 g_free(buf2);
1097         }
1098
1099         textview = GTK_TEXT_VIEW(compose->text);
1100         textbuf = gtk_text_view_get_buffer(textview);
1101
1102         if (as_attach) {
1103                 gchar *msgfile;
1104
1105                 msgfile = procmsg_get_message_file_path(msginfo);
1106                 if (!is_file_exist(msgfile))
1107                         g_warning("%s: file not exist\n", msgfile);
1108                 else
1109                         compose_attach_append(compose, msgfile, msgfile,
1110                                               "message/rfc822");
1111
1112                 g_free(msgfile);
1113         } else {
1114                 gchar *qmark;
1115                 MsgInfo *full_msginfo;
1116
1117                 full_msginfo = procmsg_msginfo_get_full_info(msginfo);
1118                 if (!full_msginfo)
1119                         full_msginfo = procmsg_msginfo_copy(msginfo);
1120
1121                 if (prefs_common.fw_quotemark &&
1122                     *prefs_common.fw_quotemark)
1123                         qmark = prefs_common.fw_quotemark;
1124                 else
1125                         qmark = "> ";
1126
1127                 compose_quote_fmt(compose, full_msginfo,
1128                                   prefs_common.fw_quotefmt,
1129                                   qmark, body);
1130                 compose_attach_parts(compose, msginfo);
1131
1132                 procmsg_msginfo_free(full_msginfo);
1133         }
1134
1135         if (account->auto_sig)
1136                 compose_insert_sig(compose, FALSE);
1137
1138         if (prefs_common.linewrap_quote)
1139                 compose_wrap_all(compose);
1140
1141         gtk_text_buffer_get_start_iter(textbuf, &iter);
1142         gtk_text_buffer_place_cursor(textbuf, &iter);
1143
1144 #if 0 /* NEW COMPOSE GUI */
1145         if (account->protocol != A_NNTP)
1146                 gtk_widget_grab_focus(compose->to_entry);
1147         else
1148                 gtk_widget_grab_focus(compose->newsgroups_entry);
1149 #endif
1150         gtk_widget_grab_focus(compose->header_last->entry);
1151
1152         if (!no_extedit && prefs_common.auto_exteditor)
1153                 compose_exec_ext_editor(compose);
1154         
1155         /*save folder*/
1156         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1157                 gchar *folderidentifier;
1158
1159                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1160                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1161                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1162                 g_free(folderidentifier);
1163         }
1164
1165         return compose;
1166 }
1167
1168 #undef INSERT_FW_HEADER
1169
1170 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1171 {
1172         Compose *compose;
1173         GtkTextView *textview;
1174         GtkTextBuffer *textbuf;
1175         GtkTextIter iter;
1176         GSList *msginfo;
1177         gchar *msgfile;
1178
1179         g_return_val_if_fail(msginfo_list != NULL, NULL);
1180
1181         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next)
1182                 if (((MsgInfo *)msginfo->data)->folder == NULL)
1183                         return NULL;
1184
1185         /* guess account from first selected message */
1186         if (!account && 
1187             !(account = compose_guess_forward_account_from_msginfo
1188                                 (msginfo_list->data)))
1189                 account = cur_account;
1190
1191         g_return_val_if_fail(account != NULL, NULL);
1192
1193         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1194                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1195                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1196         }
1197
1198         compose = compose_create(account, COMPOSE_FORWARD);
1199
1200         textview = GTK_TEXT_VIEW(compose->text);
1201         textbuf = gtk_text_view_get_buffer(textview);
1202
1203         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1204                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1205                 if (!is_file_exist(msgfile))
1206                         g_warning("%s: file not exist\n", msgfile);
1207                 else
1208                         compose_attach_append(compose, msgfile, msgfile,
1209                                 "message/rfc822");
1210                 g_free(msgfile);
1211         }
1212
1213         if (account->auto_sig)
1214                 compose_insert_sig(compose, FALSE);
1215
1216         if (prefs_common.linewrap_quote)
1217                 compose_wrap_all(compose);
1218
1219         gtk_text_buffer_get_start_iter(textbuf, &iter);
1220         gtk_text_buffer_place_cursor(textbuf, &iter);
1221
1222         gtk_widget_grab_focus(compose->header_last->entry);
1223         
1224 #if 0 /* NEW COMPOSE GUI */
1225         if (account->protocol != A_NNTP)
1226                 gtk_widget_grab_focus(compose->to_entry);
1227         else
1228                 gtk_widget_grab_focus(compose->newsgroups_entry);
1229 #endif
1230
1231         return compose;
1232 }
1233
1234 void compose_reedit(MsgInfo *msginfo)
1235 {
1236         Compose *compose;
1237         PrefsAccount *account = NULL;
1238         GtkTextView *textview;
1239         GtkTextBuffer *textbuf;
1240         GtkTextMark *mark;
1241         GtkTextIter iter;
1242         FILE *fp;
1243         gchar buf[BUFFSIZE];
1244         gboolean use_signing = FALSE;
1245         gboolean use_encryption = FALSE;
1246         gchar *privacy_system = NULL;
1247
1248         g_return_if_fail(msginfo != NULL);
1249         g_return_if_fail(msginfo->folder != NULL);
1250
1251         if (compose_put_existing_to_front(msginfo)) 
1252                 return;
1253
1254         if (msginfo->folder->stype == F_QUEUE || msginfo->folder->stype == F_DRAFT) {
1255                 gchar queueheader_buf[BUFFSIZE];
1256                 gint id, param;
1257
1258                 /* Select Account from queue headers */
1259                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1260                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1261                         id = atoi(&queueheader_buf[strlen("X-Sylpheed-Account-Id:")]);
1262                         account = account_find_from_id(id);
1263                 }
1264                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1265                                              sizeof(queueheader_buf), "NAID:")) {
1266                         id = atoi(&queueheader_buf[strlen("NAID:")]);
1267                         account = account_find_from_id(id);
1268                 }
1269                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1270                                                     sizeof(queueheader_buf), "MAID:")) {
1271                         id = atoi(&queueheader_buf[strlen("MAID:")]);
1272                         account = account_find_from_id(id);
1273                 }
1274                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1275                                                                 sizeof(queueheader_buf), "S:")) {
1276                         account = account_find_from_address(queueheader_buf);
1277                 }
1278                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1279                                              sizeof(queueheader_buf), "X-Sylpheed-Sign:")) {
1280                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Sign:")]);
1281                         use_signing = param;
1282                         
1283                 }
1284                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1285                                              sizeof(queueheader_buf), "X-Sylpheed-Encrypt:")) {
1286                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Encrypt:")]);
1287                         use_encryption = param;
1288                 }
1289                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1290                                             sizeof(queueheader_buf), "X-Sylpheed-Privacy-System:")) {
1291                         privacy_system = g_strdup(&queueheader_buf[strlen("X-Sylpheed-Privacy-System:")]);
1292                 }
1293                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1294                                              sizeof(queueheader_buf), "X-Priority: ")) {
1295                         param = atoi(&queueheader_buf[strlen("X-Priority: ")]); /* mind the space */
1296                         compose->priority = param;
1297                 }
1298         } else 
1299                 account = msginfo->folder->folder->account;
1300
1301         if (!account && prefs_common.reedit_account_autosel) {
1302                 gchar from[BUFFSIZE];
1303                 if (!procheader_get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1304                         extract_address(from);
1305                         account = account_find_from_address(from);
1306                 }
1307         }
1308         if (!account) account = cur_account;
1309         g_return_if_fail(account != NULL);
1310
1311         compose = compose_create(account, COMPOSE_REEDIT);
1312         compose->privacy_system = privacy_system;
1313         compose_use_signing(compose, use_signing);
1314         compose_use_encryption(compose, use_encryption);
1315         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1316
1317         if (msginfo->folder->stype == F_QUEUE
1318         ||  msginfo->folder->stype == F_DRAFT) {
1319                 gchar queueheader_buf[BUFFSIZE];
1320
1321                 /* Set message save folder */
1322                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1323                         gint startpos = 0;
1324
1325                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1326                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1327                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1328                 }
1329         }
1330         
1331         if (compose_parse_header(compose, msginfo) < 0) return;
1332         compose_reedit_set_entry(compose, msginfo);
1333
1334         textview = GTK_TEXT_VIEW(compose->text);
1335         textbuf = gtk_text_view_get_buffer(textview);
1336         mark = gtk_text_buffer_get_insert(textbuf);
1337         gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1338
1339         g_signal_handlers_block_by_func(G_OBJECT(textbuf),
1340                                         G_CALLBACK(compose_changed_cb),
1341                                         compose);
1342                                         
1343         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1344                 g_warning("Can't get text part\n");
1345         else {
1346                 gboolean prev_autowrap = compose->autowrap;
1347
1348                 compose->autowrap = FALSE;
1349                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1350                         strcrchomp(buf);
1351                         gtk_text_buffer_insert(textbuf, &iter, buf, -1);
1352                 }
1353                 compose->autowrap = prev_autowrap;
1354                 fclose(fp);
1355         }
1356         
1357         compose_attach_parts(compose, msginfo);
1358
1359         g_signal_handlers_unblock_by_func(G_OBJECT(textbuf),
1360                                         G_CALLBACK(compose_changed_cb),
1361                                         compose);
1362
1363         gtk_widget_grab_focus(compose->text);
1364
1365         if (prefs_common.auto_exteditor)
1366                 compose_exec_ext_editor(compose);
1367 }
1368
1369 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
1370 {
1371         Compose *compose;
1372         gchar *filename;
1373         GtkItemFactory *ifactory;
1374         FolderItem *item;
1375
1376         g_return_val_if_fail(msginfo != NULL, NULL);
1377
1378         if (!account)
1379                 account = account_get_reply_account(msginfo,
1380                                         prefs_common.reply_account_autosel);
1381         g_return_val_if_fail(account != NULL, NULL);
1382
1383         compose = compose_create(account, COMPOSE_REDIRECT);
1384         ifactory = gtk_item_factory_from_widget(compose->menubar);
1385
1386         compose->replyinfo = NULL;
1387         compose->fwdinfo = NULL;
1388
1389         compose_show_first_last_header(compose, TRUE);
1390
1391         gtk_widget_grab_focus(compose->header_last->entry);
1392
1393         filename = procmsg_get_message_file_path(msginfo);
1394         if (filename == NULL)
1395                 return NULL;
1396
1397         compose->redirect_filename = filename;
1398         
1399         /* Set save folder */
1400         item = msginfo->folder;
1401         if (item && item->prefs && item->prefs->save_copy_to_folder) {
1402                 gchar *folderidentifier;
1403
1404                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
1405                 folderidentifier = folder_item_get_identifier(item);
1406                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1407                 g_free(folderidentifier);
1408         }
1409
1410         compose_attach_parts(compose, msginfo);
1411
1412         if (msginfo->subject)
1413                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1414                                    msginfo->subject);
1415         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1416
1417         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL);
1418         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), FALSE);
1419
1420         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1421         menu_set_sensitive(ifactory, "/Add...", FALSE);
1422         menu_set_sensitive(ifactory, "/Remove", FALSE);
1423         menu_set_sensitive(ifactory, "/Properties...", FALSE);
1424
1425         ifactory = gtk_item_factory_from_widget(compose->menubar);
1426         menu_set_sensitive(ifactory, "/Message/Save", FALSE);
1427         menu_set_sensitive(ifactory, "/Message/Insert file", FALSE);
1428         menu_set_sensitive(ifactory, "/Message/Attach file", FALSE);
1429         menu_set_sensitive(ifactory, "/Message/Insert signature", FALSE);
1430         menu_set_sensitive(ifactory, "/Edit", FALSE);
1431         menu_set_sensitive(ifactory, "/Options", FALSE);
1432         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1433         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1434         
1435         gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1436         gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1437         gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1438         gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1439         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1440         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, FALSE);
1441         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, FALSE);
1442
1443         return compose;
1444 }
1445
1446 GList *compose_get_compose_list(void)
1447 {
1448         return compose_list;
1449 }
1450
1451 void compose_entry_append(Compose *compose, const gchar *address,
1452                           ComposeEntryType type)
1453 {
1454         gchar *header;
1455         gchar **parts = g_strsplit(address, ",", 0);
1456         int i = 0;
1457         if (!address || *address == '\0') return;
1458
1459         switch (type) {
1460         case COMPOSE_CC:
1461                 header = N_("Cc:");
1462                 break;
1463         case COMPOSE_BCC:
1464                 header = N_("Bcc:");
1465                 break;
1466         case COMPOSE_REPLYTO:
1467                 header = N_("Reply-To:");
1468                 break;
1469         case COMPOSE_NEWSGROUPS:
1470                 header = N_("Newsgroups:");
1471                 break;
1472         case COMPOSE_FOLLOWUPTO:
1473                 header = N_( "Followup-To:");
1474                 break;
1475         case COMPOSE_TO:
1476         default:
1477                 header = N_("To:");
1478                 break;
1479         }
1480         header = prefs_common.trans_hdr ? gettext(header) : header;
1481         while (parts[i] && *parts[i]) {
1482                 gchar *tmp = parts[i];
1483                 while (*tmp == ' ')
1484                         tmp++;
1485                 compose_add_header_entry(compose, header, tmp);
1486                 i++;
1487         }
1488         g_strfreev(parts);
1489 }
1490
1491 void compose_entry_mark_default_to(Compose *compose, const gchar *mailto)
1492 {
1493         static GtkStyle *bold_style = NULL;
1494         static GdkColor bold_color;
1495         GSList *h_list;
1496         GtkEntry *entry;
1497                 
1498         for (h_list = compose->header_list; h_list != NULL; h_list = h_list->next) {
1499                 entry = GTK_ENTRY(((ComposeHeaderEntry *)h_list->data)->entry);
1500                 if (gtk_entry_get_text(entry) && 
1501                     !g_utf8_collate(gtk_entry_get_text(entry), mailto)) {
1502                         gtk_widget_ensure_style(GTK_WIDGET(entry));
1503                         if (!bold_style) {
1504                                 PangoFontDescription *font_desc = NULL;
1505                                 gtkut_convert_int_to_gdk_color
1506                                         (prefs_common.color_new, &bold_color);
1507                                 bold_style = gtk_style_copy(gtk_widget_get_style
1508                                         (GTK_WIDGET(entry)));
1509                                 if (BOLD_FONT)
1510                                         font_desc = pango_font_description_from_string
1511                                                         (BOLD_FONT);
1512                                 if (font_desc) {
1513                                         if (bold_style->font_desc)
1514                                                 pango_font_description_free
1515                                                         (bold_style->font_desc);
1516                                         bold_style->font_desc = font_desc;
1517                                 }
1518                                 bold_style->fg[GTK_STATE_NORMAL] = bold_color;
1519                         }
1520                         gtk_widget_set_style(GTK_WIDGET(entry), bold_style);
1521                 }
1522         }
1523 }
1524
1525 void compose_toolbar_cb(gint action, gpointer data)
1526 {
1527         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1528         Compose *compose = (Compose*)toolbar_item->parent;
1529         
1530         g_return_if_fail(compose != NULL);
1531
1532         switch(action) {
1533         case A_SEND:
1534                 compose_send_cb(compose, 0, NULL);
1535                 break;
1536         case A_SENDL:
1537                 compose_send_later_cb(compose, 0, NULL);
1538                 break;
1539         case A_DRAFT:
1540                 compose_draft_cb(compose, COMPOSE_QUIT_EDITING, NULL);
1541                 break;
1542         case A_INSERT:
1543                 compose_insert_file_cb(compose, 0, NULL);
1544                 break;
1545         case A_ATTACH:
1546                 compose_attach_cb(compose, 0, NULL);
1547                 break;
1548         case A_SIG:
1549                 compose_insert_sig(compose, FALSE);
1550                 break;
1551         case A_EXTEDITOR:
1552                 compose_ext_editor_cb(compose, 0, NULL);
1553                 break;
1554         case A_LINEWRAP_CURRENT:
1555                 compose_wrap_paragraph(compose, NULL);
1556                 break;
1557         case A_LINEWRAP_ALL:
1558                 compose_wrap_all(compose);
1559                 break;
1560         case A_ADDRBOOK:
1561                 compose_address_cb(compose, 0, NULL);
1562                 break;
1563 #ifdef USE_ASPELL
1564         case A_CHECK_SPELLING:
1565                 compose_check_all(compose);
1566                 break;
1567 #endif
1568         default:
1569                 break;
1570         }
1571 }
1572
1573 static void compose_entries_set(Compose *compose, const gchar *mailto)
1574 {
1575         gchar *to = NULL;
1576         gchar *cc = NULL;
1577         gchar *subject = NULL;
1578         gchar *body = NULL;
1579         gchar *temp = NULL;
1580         gint  len = 0;
1581
1582         scan_mailto_url(mailto, &to, &cc, NULL, &subject, &body);
1583
1584         if (to)
1585                 compose_entry_append(compose, to, COMPOSE_TO);
1586         if (cc)
1587                 compose_entry_append(compose, cc, COMPOSE_CC);
1588         if (subject)
1589                 if (!g_utf8_validate (subject, -1, NULL)) {
1590                         temp = g_locale_to_utf8 (subject, -1, NULL, &len, NULL);
1591                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), temp);
1592                         g_free(temp);
1593                 } else {
1594                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1595                 }
1596         if (body) {
1597                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1598                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1599                 GtkTextMark *mark;
1600                 GtkTextIter iter;
1601                 gboolean prev_autowrap = compose->autowrap;
1602
1603                 compose->autowrap = FALSE;
1604
1605                 mark = gtk_text_buffer_get_insert(buffer);
1606                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1607
1608                 if (!g_utf8_validate (body, -1, NULL)) {
1609                         temp = g_locale_to_utf8 (body, -1, NULL, &len, NULL);
1610                         gtk_text_buffer_insert(buffer, &iter, temp, -1);
1611                         g_free(temp);
1612                 } else {
1613                         gtk_text_buffer_insert(buffer, &iter, body, -1);
1614                 }
1615                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
1616
1617                 compose->autowrap = prev_autowrap;
1618                 if (compose->autowrap)
1619                         compose_wrap_all(compose);
1620         }
1621
1622         g_free(to);
1623         g_free(cc);
1624         g_free(subject);
1625         g_free(body);
1626 }
1627
1628 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1629 {
1630         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1631                                        {"Cc:",          NULL, TRUE},
1632                                        {"References:",  NULL, FALSE},
1633                                        {"Bcc:",         NULL, TRUE},
1634                                        {"Newsgroups:",  NULL, TRUE},
1635                                        {"Followup-To:", NULL, TRUE},
1636                                        {"List-Post:",   NULL, FALSE},
1637                                        {"X-Priority:",  NULL, FALSE},
1638                                        {NULL,           NULL, FALSE}};
1639
1640         enum
1641         {
1642                 H_REPLY_TO      = 0,
1643                 H_CC            = 1,
1644                 H_REFERENCES    = 2,
1645                 H_BCC           = 3,
1646                 H_NEWSGROUPS    = 4,
1647                 H_FOLLOWUP_TO   = 5,
1648                 H_LIST_POST     = 6,
1649                 H_X_PRIORITY    = 7
1650         };
1651
1652         FILE *fp;
1653
1654         g_return_val_if_fail(msginfo != NULL, -1);
1655
1656         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1657         procheader_get_header_fields(fp, hentry);
1658         fclose(fp);
1659
1660         if (hentry[H_REPLY_TO].body != NULL) {
1661                 if (hentry[H_REPLY_TO].body[0] != '\0') {
1662                         compose->replyto =
1663                                 conv_unmime_header(hentry[H_REPLY_TO].body,
1664                                                    NULL);
1665                 }
1666                 g_free(hentry[H_REPLY_TO].body);
1667                 hentry[H_REPLY_TO].body = NULL;
1668         }
1669         if (hentry[H_CC].body != NULL) {
1670                 compose->cc = conv_unmime_header(hentry[H_CC].body, NULL);
1671                 g_free(hentry[H_CC].body);
1672                 hentry[H_CC].body = NULL;
1673         }
1674         if (hentry[H_REFERENCES].body != NULL) {
1675                 if (compose->mode == COMPOSE_REEDIT)
1676                         compose->references = hentry[H_REFERENCES].body;
1677                 else {
1678                         compose->references = compose_parse_references
1679                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1680                         g_free(hentry[H_REFERENCES].body);
1681                 }
1682                 hentry[H_REFERENCES].body = NULL;
1683         }
1684         if (hentry[H_BCC].body != NULL) {
1685                 if (compose->mode == COMPOSE_REEDIT)
1686                         compose->bcc =
1687                                 conv_unmime_header(hentry[H_BCC].body, NULL);
1688                 g_free(hentry[H_BCC].body);
1689                 hentry[H_BCC].body = NULL;
1690         }
1691         if (hentry[H_NEWSGROUPS].body != NULL) {
1692                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1693                 hentry[H_NEWSGROUPS].body = NULL;
1694         }
1695         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1696                 if (hentry[H_FOLLOWUP_TO].body[0] != '\0') {
1697                         compose->followup_to =
1698                                 conv_unmime_header(hentry[H_FOLLOWUP_TO].body,
1699                                                    NULL);
1700                 }
1701                 g_free(hentry[H_FOLLOWUP_TO].body);
1702                 hentry[H_FOLLOWUP_TO].body = NULL;
1703         }
1704         if (hentry[H_LIST_POST].body != NULL) {
1705                 gchar *to = NULL;
1706
1707                 extract_address(hentry[H_LIST_POST].body);
1708                 if (hentry[H_LIST_POST].body[0] != '\0') {
1709                         scan_mailto_url(hentry[H_LIST_POST].body,
1710                                         &to, NULL, NULL, NULL, NULL);
1711                         if (to) {
1712                                 g_free(compose->ml_post);
1713                                 compose->ml_post = to;
1714                         }
1715                 }
1716                 g_free(hentry[H_LIST_POST].body);
1717                 hentry[H_LIST_POST].body = NULL;
1718         }
1719
1720         /* CLAWS - X-Priority */
1721         if (compose->mode == COMPOSE_REEDIT)
1722                 if (hentry[H_X_PRIORITY].body != NULL) {
1723                         gint priority;
1724                         
1725                         priority = atoi(hentry[H_X_PRIORITY].body);
1726                         g_free(hentry[H_X_PRIORITY].body);
1727                         
1728                         hentry[H_X_PRIORITY].body = NULL;
1729                         
1730                         if (priority < PRIORITY_HIGHEST || 
1731                             priority > PRIORITY_LOWEST)
1732                                 priority = PRIORITY_NORMAL;
1733                         
1734                         compose->priority =  priority;
1735                 }
1736  
1737         if (compose->mode == COMPOSE_REEDIT) {
1738                 if (msginfo->inreplyto && *msginfo->inreplyto)
1739                         compose->inreplyto = g_strdup(msginfo->inreplyto);
1740                 return 0;
1741         }
1742
1743         if (msginfo->msgid && *msginfo->msgid)
1744                 compose->inreplyto = g_strdup(msginfo->msgid);
1745
1746         if (!compose->references) {
1747                 if (msginfo->msgid && *msginfo->msgid) {
1748                         if (msginfo->inreplyto && *msginfo->inreplyto)
1749                                 compose->references =
1750                                         g_strdup_printf("<%s>\n\t<%s>",
1751                                                         msginfo->inreplyto,
1752                                                         msginfo->msgid);
1753                         else
1754                                 compose->references =
1755                                         g_strconcat("<", msginfo->msgid, ">",
1756                                                     NULL);
1757                 } else if (msginfo->inreplyto && *msginfo->inreplyto) {
1758                         compose->references =
1759                                 g_strconcat("<", msginfo->inreplyto, ">",
1760                                             NULL);
1761                 }
1762         }
1763
1764         return 0;
1765 }
1766
1767 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1768 {
1769         GSList *ref_id_list, *cur;
1770         GString *new_ref;
1771         gchar *new_ref_str;
1772
1773         ref_id_list = references_list_append(NULL, ref);
1774         if (!ref_id_list) return NULL;
1775         if (msgid && *msgid)
1776                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1777
1778         for (;;) {
1779                 gint len = 0;
1780
1781                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1782                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1783                         len += strlen((gchar *)cur->data) + 5;
1784
1785                 if (len > MAX_REFERENCES_LEN) {
1786                         /* remove second message-ID */
1787                         if (ref_id_list && ref_id_list->next &&
1788                             ref_id_list->next->next) {
1789                                 g_free(ref_id_list->next->data);
1790                                 ref_id_list = g_slist_remove
1791                                         (ref_id_list, ref_id_list->next->data);
1792                         } else {
1793                                 slist_free_strings(ref_id_list);
1794                                 g_slist_free(ref_id_list);
1795                                 return NULL;
1796                         }
1797                 } else
1798                         break;
1799         }
1800
1801         new_ref = g_string_new("");
1802         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1803                 if (new_ref->len > 0)
1804                         g_string_append(new_ref, "\n\t");
1805                 g_string_append_printf(new_ref, "<%s>", (gchar *)cur->data);
1806         }
1807
1808         slist_free_strings(ref_id_list);
1809         g_slist_free(ref_id_list);
1810
1811         new_ref_str = new_ref->str;
1812         g_string_free(new_ref, FALSE);
1813
1814         return new_ref_str;
1815 }
1816
1817 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1818                                 const gchar *fmt, const gchar *qmark,
1819                                 const gchar *body)
1820 {
1821         static MsgInfo dummyinfo;
1822         gchar *quote_str = NULL;
1823         gchar *buf;
1824         gchar *p, *lastp;
1825         gint len;
1826         gboolean prev_autowrap;
1827         const gchar *trimmed_body = body;
1828         
1829         if (!msginfo)
1830                 msginfo = &dummyinfo;
1831
1832         if (qmark != NULL) {
1833                 quote_fmt_init(msginfo, NULL, NULL);
1834                 quote_fmt_scan_string(qmark);
1835                 quote_fmt_parse();
1836
1837                 buf = quote_fmt_get_buffer();
1838                 if (buf == NULL)
1839                         alertpanel_error(_("Quote mark format error."));
1840                 else
1841                         Xstrdup_a(quote_str, buf, return NULL)
1842         }
1843
1844         if (fmt && *fmt != '\0') {
1845                 while (trimmed_body && strlen(trimmed_body) > 1
1846                         && trimmed_body[0]=='\n')
1847                         *trimmed_body++;
1848
1849                 quote_fmt_init(msginfo, quote_str, trimmed_body);
1850                 quote_fmt_scan_string(fmt);
1851                 quote_fmt_parse();
1852
1853                 buf = quote_fmt_get_buffer();
1854                 if (buf == NULL) {
1855                         alertpanel_error(_("Message reply/forward format error."));
1856                         return NULL;
1857                 }
1858         } else
1859                 buf = "";
1860
1861         prev_autowrap = compose->autowrap;
1862         compose->autowrap = FALSE;
1863
1864         for (p = buf; *p != '\0'; ) {
1865                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1866                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1867                 GtkTextMark *mark;
1868                 GtkTextIter iter;
1869
1870                 g_signal_handlers_block_by_func(G_OBJECT(buffer),
1871                                         G_CALLBACK(compose_changed_cb),
1872                                         compose);
1873                 g_signal_handlers_block_by_func(G_OBJECT(buffer),
1874                                         G_CALLBACK(text_inserted),
1875                                         compose);
1876                 
1877                 mark = gtk_text_buffer_get_insert(buffer);
1878                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1879
1880                 lastp = strchr(p, '\n');
1881                 len = lastp ? lastp - p + 1 : -1;
1882
1883                 gtk_text_buffer_insert(buffer, &iter, p, len);
1884
1885                 g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
1886                                         G_CALLBACK(compose_changed_cb),
1887                                         compose);
1888                 g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
1889                                         G_CALLBACK(text_inserted),
1890                                         compose);
1891                 
1892                 if (lastp)
1893                         p = lastp + 1;
1894                 else
1895                         break;
1896         }
1897
1898         compose->autowrap = prev_autowrap;
1899         if (compose->autowrap)
1900                 compose_wrap_all(compose);
1901
1902         return buf;
1903 }
1904
1905 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1906                                     gboolean to_all, gboolean to_ml,
1907                                     gboolean to_sender,
1908                                     gboolean followup_and_reply_to)
1909 {
1910         GSList *cc_list = NULL;
1911         GSList *cur;
1912         gchar *from = NULL;
1913         gchar *replyto = NULL;
1914         GHashTable *to_table;
1915
1916         g_return_if_fail(compose->account != NULL);
1917         g_return_if_fail(msginfo != NULL);
1918
1919         if (compose->account->protocol != A_NNTP) {
1920                 if (!compose->replyto && to_ml && compose->ml_post
1921                     && !(msginfo->folder && msginfo->folder->prefs->enable_default_reply_to))
1922                         compose_entry_append(compose,
1923                                            compose->ml_post,
1924                                            COMPOSE_TO);
1925                 else if (!(to_all || to_sender)
1926                          && msginfo->folder
1927                          && msginfo->folder->prefs->enable_default_reply_to) {
1928                         compose_entry_append(compose,
1929                             msginfo->folder->prefs->default_reply_to,
1930                             COMPOSE_TO);
1931                 } else
1932                         compose_entry_append(compose,
1933                                  (compose->replyto && !to_sender)
1934                                   ? compose->replyto :
1935                                   msginfo->from ? msginfo->from : "",
1936                                   COMPOSE_TO);
1937         } else {
1938                 if (to_sender || (compose->followup_to && 
1939                         !strncmp(compose->followup_to, "poster", 6)))
1940                         compose_entry_append
1941                                 (compose, 
1942                                  (compose->replyto ? compose->replyto :
1943                                         msginfo->from ? msginfo->from : ""),
1944                                  COMPOSE_TO);
1945                                  
1946                 else if (followup_and_reply_to || to_all) {
1947                         compose_entry_append
1948                                 (compose,
1949                                  (compose->replyto ? compose->replyto :
1950                                  msginfo->from ? msginfo->from : ""),
1951                                  COMPOSE_TO);                           
1952                 
1953                         compose_entry_append
1954                                 (compose,
1955                                  compose->followup_to ? compose->followup_to :
1956                                  compose->newsgroups ? compose->newsgroups : "",
1957                                  COMPOSE_NEWSGROUPS);
1958                 } 
1959                 else 
1960                         compose_entry_append
1961                                 (compose,
1962                                  compose->followup_to ? compose->followup_to :
1963                                  compose->newsgroups ? compose->newsgroups : "",
1964                                  COMPOSE_NEWSGROUPS);
1965         }
1966
1967         if (msginfo->subject && *msginfo->subject) {
1968                 gchar *buf, *buf2;
1969                 guchar *p;
1970
1971                 buf = p = g_strdup(msginfo->subject);
1972                 p += subject_get_prefix_length(p);
1973                 memmove(buf, p, strlen(p) + 1);
1974
1975                 buf2 = g_strdup_printf("Re: %s", buf);
1976                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1977
1978                 g_free(buf2);
1979                 g_free(buf);
1980         } else
1981                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1982
1983         if (to_ml && compose->ml_post) return;
1984         if (!to_all || compose->account->protocol == A_NNTP) return;
1985
1986         if (compose->replyto) {
1987                 Xstrdup_a(replyto, compose->replyto, return);
1988                 extract_address(replyto);
1989         }
1990         if (msginfo->from) {
1991                 Xstrdup_a(from, msginfo->from, return);
1992                 extract_address(from);
1993         }
1994
1995         if (replyto && from)
1996                 cc_list = address_list_append_with_comments(cc_list, from);
1997         if (to_all && msginfo->folder && 
1998             msginfo->folder->prefs->enable_default_reply_to)
1999                 cc_list = address_list_append_with_comments(cc_list,
2000                                 msginfo->folder->prefs->default_reply_to);
2001         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
2002         cc_list = address_list_append_with_comments(cc_list, compose->cc);
2003
2004         to_table = g_hash_table_new(g_str_hash, g_str_equal);
2005         if (replyto)
2006                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
2007         if (compose->account)
2008                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
2009                                     GINT_TO_POINTER(1));
2010
2011         /* remove address on To: and that of current account */
2012         for (cur = cc_list; cur != NULL; ) {
2013                 GSList *next = cur->next;
2014                 gchar *addr;
2015
2016                 addr = g_strdup(cur->data);
2017                 extract_address(addr);
2018
2019                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
2020                         cc_list = g_slist_remove(cc_list, cur->data);
2021                 else
2022                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
2023
2024                 cur = next;
2025         }
2026         hash_free_strings(to_table);
2027         g_hash_table_destroy(to_table);
2028
2029         if (cc_list) {
2030                 for (cur = cc_list; cur != NULL; cur = cur->next)
2031                         compose_entry_append(compose, (gchar *)cur->data,
2032                                              COMPOSE_CC);
2033                 slist_free_strings(cc_list);
2034                 g_slist_free(cc_list);
2035         }
2036
2037 }
2038
2039 #define SET_ENTRY(entry, str) \
2040 { \
2041         if (str && *str) \
2042                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
2043 }
2044
2045 #define SET_ADDRESS(type, str) \
2046 { \
2047         if (str && *str) \
2048                 compose_entry_append(compose, str, type); \
2049 }
2050
2051 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
2052 {
2053         g_return_if_fail(msginfo != NULL);
2054
2055         SET_ENTRY(subject_entry, msginfo->subject);
2056         SET_ADDRESS(COMPOSE_TO, msginfo->to);
2057         SET_ADDRESS(COMPOSE_CC, compose->cc);
2058         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
2059         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
2060         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
2061         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2062
2063         compose_update_priority_menu_item(compose);
2064         compose_update_privacy_system_menu_item(compose);
2065         compose_show_first_last_header(compose, TRUE);
2066 }
2067
2068 #undef SET_ENTRY
2069 #undef SET_ADDRESS
2070
2071 static void compose_insert_sig(Compose *compose, gboolean replace)
2072 {
2073         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2074         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2075         GtkTextMark *mark;
2076         GtkTextIter iter;
2077         gint cur_pos;
2078         gboolean prev_autowrap;
2079
2080         
2081         g_return_if_fail(compose->account != NULL);
2082
2083         prev_autowrap = compose->autowrap;
2084         compose->autowrap = FALSE;
2085
2086         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2087                                         G_CALLBACK(compose_changed_cb),
2088                                         compose);
2089         
2090         mark = gtk_text_buffer_get_insert(buffer);
2091         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2092         cur_pos = gtk_text_iter_get_offset (&iter);
2093
2094         gtk_text_buffer_get_end_iter(buffer, &iter);
2095
2096         if (replace && compose->sig_str) {
2097                 gboolean found;
2098                 GtkTextIter first_iter, start_iter, end_iter;
2099
2100                 gtk_text_buffer_get_start_iter(buffer, &first_iter);
2101
2102                 if (compose->sig_str[0] == '\0')
2103                         found = FALSE;
2104                 else
2105                         found = gtk_text_iter_forward_search(&first_iter,
2106                                                              compose->sig_str,
2107                                                              GTK_TEXT_SEARCH_TEXT_ONLY,
2108                                                              &start_iter, &end_iter,
2109                                                              NULL);
2110
2111                 if (found) {
2112                         gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
2113                         iter = start_iter;
2114                 }
2115         }
2116
2117         g_free(compose->sig_str);
2118         compose->sig_str = compose_get_signature_str(compose);
2119         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2120                 compose->sig_str = g_strdup("");
2121
2122         gtk_text_buffer_insert(buffer, &iter, compose->sig_str, -1);
2123
2124         if (cur_pos > gtk_text_buffer_get_char_count (buffer))
2125                 cur_pos = gtk_text_buffer_get_char_count (buffer);
2126
2127         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2128         gtk_text_buffer_place_cursor(buffer, &iter);
2129
2130         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2131                                         G_CALLBACK(compose_changed_cb),
2132                                         compose);
2133         
2134         compose->autowrap = prev_autowrap;
2135         if (compose->autowrap)
2136                 compose_wrap_all(compose);
2137 }
2138
2139 static gchar *compose_get_signature_str(Compose *compose)
2140 {
2141         gchar *sig_body = NULL;
2142         gchar *sig_str = NULL;
2143         gchar *utf8_sig_str = NULL;
2144
2145         g_return_val_if_fail(compose->account != NULL, NULL);
2146
2147         if (!compose->account->sig_path)
2148                 return NULL;
2149
2150         if (compose->account->sig_type == SIG_FILE) {
2151                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2152                         g_warning("can't open signature file: %s\n",
2153                                   compose->account->sig_path);
2154                         return NULL;
2155                 }
2156         }
2157
2158         if (compose->account->sig_type == SIG_COMMAND)
2159                 sig_body = get_command_output(compose->account->sig_path);
2160         else {
2161                 gchar *tmp;
2162
2163                 tmp = file_read_to_str(compose->account->sig_path);
2164                 if (!tmp)
2165                         return NULL;
2166                 sig_body = normalize_newlines(tmp);
2167                 g_free(tmp);
2168         }
2169
2170         if (compose->account->sig_sep) {
2171                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2172                                       NULL);
2173                 g_free(sig_body);
2174         } else
2175                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2176
2177         if (sig_str) {
2178                 if (!g_utf8_validate(sig_str,1, NULL)) {
2179                         utf8_sig_str = conv_codeset_strdup
2180                                 (sig_str, conv_get_locale_charset_str(), CS_INTERNAL);
2181                         g_free(sig_str);
2182                 } else
2183                         utf8_sig_str = sig_str;
2184         }
2185
2186         return utf8_sig_str;
2187 }
2188
2189 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2190 {
2191         GtkTextView *text;
2192         GtkTextBuffer *buffer;
2193         GtkTextMark *mark;
2194         GtkTextIter iter;
2195         const gchar *cur_encoding;
2196         gchar buf[BUFFSIZE];
2197         gint len;
2198         FILE *fp;
2199         gboolean prev_autowrap;
2200         gboolean badtxt = FALSE;
2201
2202         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2203
2204         if ((fp = fopen(file, "rb")) == NULL) {
2205                 FILE_OP_ERROR(file, "fopen");
2206                 return COMPOSE_INSERT_READ_ERROR;
2207         }
2208
2209         prev_autowrap = compose->autowrap;
2210         compose->autowrap = FALSE;
2211
2212         text = GTK_TEXT_VIEW(compose->text);
2213         buffer = gtk_text_view_get_buffer(text);
2214         mark = gtk_text_buffer_get_insert(buffer);
2215         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2216
2217         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2218                                         G_CALLBACK(text_inserted),
2219                                         compose);
2220
2221         cur_encoding = conv_get_locale_charset_str();
2222
2223         while (fgets(buf, sizeof(buf), fp) != NULL) {
2224                 gchar *str;
2225
2226                 str = conv_codeset_strdup(buf, cur_encoding, CS_INTERNAL);
2227                 if (!str) continue;
2228
2229                 /* strip <CR> if DOS/Windows file,
2230                    replace <CR> with <LF> if Macintosh file. */
2231                 strcrchomp(str);
2232                 len = strlen(str);
2233                 if (len > 0 && str[len - 1] != '\n') {
2234                         while (--len >= 0)
2235                                 if (str[len] == '\r') str[len] = '\n';
2236                 }
2237
2238                 gtk_text_buffer_insert(buffer, &iter, str, -1);
2239                 g_free(str);
2240         }
2241
2242         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2243                                           G_CALLBACK(text_inserted),
2244                                           compose);
2245         compose->autowrap = prev_autowrap;
2246         if (compose->autowrap)
2247                 compose_wrap_all(compose);
2248
2249         fclose(fp);
2250
2251         if (badtxt)
2252                 return COMPOSE_INSERT_INVALID_CHARACTER;
2253         else 
2254                 return COMPOSE_INSERT_SUCCESS;
2255 }
2256
2257 static void compose_attach_append(Compose *compose, const gchar *file,
2258                                   const gchar *filename,
2259                                   const gchar *content_type)
2260 {
2261         AttachInfo *ainfo;
2262         GtkTreeIter iter;
2263         FILE *fp;
2264         off_t size;
2265         GAuto *auto_ainfo;
2266         gchar *size_text;
2267         GtkListStore *store;
2268         gchar *name;
2269
2270         if (!is_file_exist(file)) {
2271                 g_warning("File %s doesn't exist\n", filename);
2272                 return;
2273         }
2274         if ((size = get_file_size(file)) < 0) {
2275                 g_warning("Can't get file size of %s\n", filename);
2276                 return;
2277         }
2278         if (size == 0) {
2279                 alertpanel_notice(_("File %s is empty."), filename);
2280                 return;
2281         }
2282         if ((fp = fopen(file, "rb")) == NULL) {
2283                 alertpanel_error(_("Can't read %s."), filename);
2284                 return;
2285         }
2286         fclose(fp);
2287
2288 #if 0 /* NEW COMPOSE GUI */
2289         if (!compose->use_attach) {
2290                 GtkItemFactory *ifactory;
2291
2292                 ifactory = gtk_item_factory_from_widget(compose->menubar);
2293                 menu_set_active(ifactory, "/View/Attachment", TRUE);
2294         }
2295 #endif
2296         ainfo = g_new0(AttachInfo, 1);
2297         auto_ainfo = g_auto_pointer_new_with_free
2298                         (ainfo, (GFreeFunc) compose_attach_info_free); 
2299         ainfo->file = g_strdup(file);
2300
2301         if (content_type) {
2302                 ainfo->content_type = g_strdup(content_type);
2303                 if (!g_ascii_strcasecmp(content_type, "message/rfc822")) {
2304                         MsgInfo *msginfo;
2305                         MsgFlags flags = {0, 0};
2306
2307                         if (procmime_get_encoding_for_text_file(file) == ENC_7BIT)
2308                                 ainfo->encoding = ENC_7BIT;
2309                         else
2310                                 ainfo->encoding = ENC_8BIT;
2311
2312                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2313                         if (msginfo && msginfo->subject)
2314                                 name = g_strdup(msginfo->subject);
2315                         else
2316                                 name = g_path_get_basename(filename ? filename : file);
2317
2318                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2319
2320                         procmsg_msginfo_free(msginfo);
2321                 } else {
2322                         if (!g_ascii_strncasecmp(content_type, "text", 4))
2323                                 ainfo->encoding = procmime_get_encoding_for_text_file(file);
2324                         else
2325                                 ainfo->encoding = ENC_BASE64;
2326                         name = g_path_get_basename(filename ? filename : file);
2327                         ainfo->name = g_strdup(name);
2328                 }
2329                 g_free(name);
2330         } else {
2331                 ainfo->content_type = procmime_get_mime_type(file);
2332                 if (!ainfo->content_type) {
2333                         ainfo->content_type =
2334                                 g_strdup("application/octet-stream");
2335                         ainfo->encoding = ENC_BASE64;
2336                 } else if (!g_ascii_strncasecmp(ainfo->content_type, "text", 4))
2337                         ainfo->encoding =
2338                                 procmime_get_encoding_for_text_file(file);
2339                 else
2340                         ainfo->encoding = ENC_BASE64;
2341                 name = g_path_get_basename(filename ? filename : file);
2342                 ainfo->name = g_strdup(name);   
2343                 g_free(name);
2344         }
2345
2346         if (!strcmp(ainfo->content_type, "unknown")) {
2347                 g_free(ainfo->content_type);
2348                 ainfo->content_type = g_strdup("application/octet-stream");
2349         }
2350
2351         ainfo->size = size;
2352         size_text = to_human_readable(size);
2353
2354         store = GTK_LIST_STORE(gtk_tree_view_get_model
2355                         (GTK_TREE_VIEW(compose->attach_clist)));
2356                 
2357         gtk_list_store_append(store, &iter);
2358         gtk_list_store_set(store, &iter, 
2359                            COL_MIMETYPE, ainfo->content_type,
2360                            COL_SIZE, size_text,
2361                            COL_NAME, ainfo->name,
2362                            COL_DATA, ainfo,
2363                            COL_AUTODATA, auto_ainfo,
2364                            -1);
2365         
2366         g_auto_pointer_free(auto_ainfo);
2367 }
2368
2369 static void compose_use_signing(Compose *compose, gboolean use_signing)
2370 {
2371         GtkItemFactory *ifactory;
2372         GtkWidget *menuitem = NULL;
2373
2374         compose->use_signing = use_signing;
2375         ifactory = gtk_item_factory_from_widget(compose->menubar);
2376         menuitem = gtk_item_factory_get_item
2377                 (ifactory, "/Options/Sign");
2378         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2379                                        use_signing);
2380 }
2381
2382 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2383 {
2384         GtkItemFactory *ifactory;
2385         GtkWidget *menuitem = NULL;
2386
2387         compose->use_encryption = use_encryption;
2388         ifactory = gtk_item_factory_from_widget(compose->menubar);
2389         menuitem = gtk_item_factory_get_item
2390                 (ifactory, "/Options/Encrypt");
2391
2392         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2393                                        use_encryption);
2394 }
2395
2396 #define NEXT_PART_NOT_CHILD(info)  \
2397 {  \
2398         node = info->node;  \
2399         while (node->children)  \
2400                 node = g_node_last_child(node);  \
2401         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2402 }
2403
2404 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2405 {
2406         MimeInfo *mimeinfo;
2407         MimeInfo *child;
2408         MimeInfo *firsttext = NULL;
2409         MimeInfo *encrypted = NULL;
2410         GNode    *node;
2411         gchar *outfile;
2412         const gchar *partname = NULL;
2413
2414         mimeinfo = procmime_scan_message(msginfo);
2415         if (!mimeinfo) return;
2416
2417         if (mimeinfo->node->children == NULL) {
2418                 procmime_mimeinfo_free_all(mimeinfo);
2419                 return;
2420         }
2421
2422         /* find first content part */
2423         child = (MimeInfo *) mimeinfo->node->children->data;
2424         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2425                 child = (MimeInfo *)child->node->children->data;
2426
2427         if (child->type == MIMETYPE_TEXT) {
2428                 firsttext = child;
2429                 debug_print("First text part found\n");
2430         } else if (compose->mode == COMPOSE_REEDIT &&
2431                  child->type == MIMETYPE_APPLICATION &&
2432                  !g_ascii_strcasecmp(child->subtype, "pgp-encrypted")) {
2433                 AlertValue val;
2434                 val = alertpanel(_("Encrypted message"),
2435                                  _("Cannot re-edit an encrypted message. \n"
2436                                    "Discard encrypted part?"),
2437                                  _("Yes"), _("No"), NULL);
2438                 if (val == G_ALERTDEFAULT) 
2439                         encrypted = (MimeInfo *)child->node->parent->data;
2440         }
2441      
2442         child = (MimeInfo *) mimeinfo->node->children->data;
2443         while (child != NULL) {
2444                 if (child == encrypted) {
2445                         /* skip this part of tree */
2446                         NEXT_PART_NOT_CHILD(child);
2447                         continue;
2448                 }
2449
2450                 if (child->type == MIMETYPE_MULTIPART) {
2451                         /* get the actual content */
2452                         child = procmime_mimeinfo_next(child);
2453                         continue;
2454                 }
2455                     
2456                 if (child == firsttext) {
2457                         child = procmime_mimeinfo_next(child);
2458                         continue;
2459                 }
2460
2461                 outfile = procmime_get_tmp_file_name(child);
2462                 if (procmime_get_part(outfile, child) < 0)
2463                         g_warning("Can't get the part of multipart message.");
2464                 else {
2465                         gchar *content_type;
2466
2467                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2468                         partname = procmime_mimeinfo_get_parameter(child, "name");
2469                         if (partname == NULL)
2470                                 partname = "";
2471                         compose_attach_append(compose, outfile, 
2472                                               partname, content_type);
2473                         g_free(content_type);
2474                 }
2475                 g_free(outfile);
2476                 NEXT_PART_NOT_CHILD(child);
2477         }
2478         procmime_mimeinfo_free_all(mimeinfo);
2479 }
2480
2481 #undef NEXT_PART_NOT_CHILD
2482
2483
2484
2485 typedef enum {
2486         WAIT_FOR_INDENT_CHAR,
2487         WAIT_FOR_INDENT_CHAR_OR_SPACE,
2488 } IndentState;
2489
2490 /* return indent length, we allow:
2491    indent characters followed by indent characters or spaces/tabs,
2492    alphabets and numbers immediately followed by indent characters,
2493    and the repeating sequences of the above
2494    If quote ends with multiple spaces, only the first one is included. */
2495 static gchar *compose_get_quote_str(GtkTextBuffer *buffer,
2496                                     const GtkTextIter *start, gint *len)
2497 {
2498         GtkTextIter iter = *start;
2499         gunichar wc;
2500         gchar ch[6];
2501         gint clen;
2502         IndentState state = WAIT_FOR_INDENT_CHAR;
2503         gboolean is_space;
2504         gboolean is_indent;
2505         gint alnum_count = 0;
2506         gint space_count = 0;
2507         gint quote_len = 0;
2508
2509         if (prefs_common.quote_chars == NULL) {
2510                 return 0 ;
2511         }
2512
2513         while (!gtk_text_iter_ends_line(&iter)) {
2514                 wc = gtk_text_iter_get_char(&iter);
2515                 if (g_unichar_iswide(wc))
2516                         break;
2517                 clen = g_unichar_to_utf8(wc, ch);
2518                 if (clen != 1)
2519                         break;
2520
2521                 is_indent = strchr(prefs_common.quote_chars, ch[0]) ? TRUE : FALSE;
2522                 is_space = g_unichar_isspace(wc);
2523
2524                 if (state == WAIT_FOR_INDENT_CHAR) {
2525                         if (!is_indent && !g_unichar_isalnum(wc))
2526                                 break;
2527                         if (is_indent) {
2528                                 quote_len += alnum_count + space_count + 1;
2529                                 alnum_count = space_count = 0;
2530                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2531                         } else
2532                                 alnum_count++;
2533                 } else if (state == WAIT_FOR_INDENT_CHAR_OR_SPACE) {
2534                         if (!is_indent && !is_space && !g_unichar_isalnum(wc))
2535                                 break;
2536                         if (is_space)
2537                                 space_count++;
2538                         else if (is_indent) {
2539                                 quote_len += alnum_count + space_count + 1;
2540                                 alnum_count = space_count = 0;
2541                         } else {
2542                                 alnum_count++;
2543                                 state = WAIT_FOR_INDENT_CHAR;
2544                         }
2545                 }
2546
2547                 gtk_text_iter_forward_char(&iter);
2548         }
2549
2550         if (quote_len > 0 && space_count > 0)
2551                 quote_len++;
2552
2553         if (len)
2554                 *len = quote_len;
2555
2556         if (quote_len > 0) {
2557                 iter = *start;
2558                 gtk_text_iter_forward_chars(&iter, quote_len);
2559                 return gtk_text_buffer_get_text(buffer, start, &iter, FALSE);
2560         }
2561
2562         return NULL;
2563 }
2564
2565 /* return TRUE if the line is itemized */
2566 static gboolean compose_is_itemized(GtkTextBuffer *buffer,
2567                                     const GtkTextIter *start)
2568 {
2569         GtkTextIter iter = *start;
2570         gunichar wc;
2571         gchar ch[6];
2572         gint clen;
2573
2574         if (gtk_text_iter_ends_line(&iter))
2575                 return FALSE;
2576
2577         while (1) {
2578                 wc = gtk_text_iter_get_char(&iter);
2579                 if (!g_unichar_isspace(wc))
2580                         break;
2581                 gtk_text_iter_forward_char(&iter);
2582                 if (gtk_text_iter_ends_line(&iter))
2583                         return FALSE;
2584         }
2585
2586         clen = g_unichar_to_utf8(wc, ch);
2587         if (clen != 1)
2588                 return FALSE;
2589
2590         if (!strchr("*-+", ch[0]))
2591                 return FALSE;
2592
2593         gtk_text_iter_forward_char(&iter);
2594         if (gtk_text_iter_ends_line(&iter))
2595                 return FALSE;
2596         wc = gtk_text_iter_get_char(&iter);
2597         if (g_unichar_isspace(wc))
2598                 return TRUE;
2599
2600         return FALSE;
2601 }
2602
2603 static gboolean compose_get_line_break_pos(GtkTextBuffer *buffer,
2604                                            const GtkTextIter *start,
2605                                            GtkTextIter *break_pos,
2606                                            gint max_col,
2607                                            gint quote_len)
2608 {
2609         GtkTextIter iter = *start, line_end = *start;
2610         PangoLogAttr *attrs;
2611         gchar *str;
2612         gchar *p;
2613         gint len;
2614         gint i;
2615         gint col = 0;
2616         gint pos = 0;
2617         gboolean can_break = FALSE;
2618         gboolean do_break = FALSE;
2619
2620         gtk_text_iter_forward_to_line_end(&line_end);
2621         str = gtk_text_buffer_get_text(buffer, &iter, &line_end, FALSE);
2622         len = g_utf8_strlen(str, -1);
2623         /* g_print("breaking line: %d: %s (len = %d)\n",
2624                 gtk_text_iter_get_line(&iter), str, len); */
2625         attrs = g_new(PangoLogAttr, len + 1);
2626
2627         pango_default_break(str, -1, NULL, attrs, len + 1);
2628
2629         p = str;
2630
2631         /* skip quote and leading spaces */
2632         for (i = 0; *p != '\0' && i < len; i++) {
2633                 gunichar wc;
2634
2635                 wc = g_utf8_get_char(p);
2636                 if (i >= quote_len && !g_unichar_isspace(wc))
2637                         break;
2638                 if (g_unichar_iswide(wc))
2639                         col += 2;
2640                 else if (*p == '\t')
2641                         col += 8;
2642                 else
2643                         col++;
2644                 p = g_utf8_next_char(p);
2645         }
2646
2647         for (; *p != '\0' && i < len; i++) {
2648                 PangoLogAttr *attr = attrs + i;
2649                 gunichar wc;
2650                 gint uri_len;
2651
2652                 if (attr->is_line_break && can_break)
2653                         pos = i;
2654
2655                 /* don't wrap URI */
2656                 if ((uri_len = get_uri_len(p)) > 0) {
2657                         col += uri_len;
2658                         if (pos > 0 && col > max_col) {
2659                                 do_break = TRUE;
2660                                 break;
2661                         }
2662                         i += uri_len - 1;
2663                         p += uri_len;
2664                         can_break = TRUE;
2665                         continue;
2666                 }
2667
2668                 wc = g_utf8_get_char(p);
2669                 if (g_unichar_iswide(wc))
2670                         col += 2;
2671                 else if (*p == '\t')
2672                         col += 8;
2673                 else
2674                         col++;
2675                 if (pos > 0 && col > max_col) {
2676                         do_break = TRUE;
2677                         break;
2678                 }
2679
2680                 p = g_utf8_next_char(p);
2681                 can_break = TRUE;
2682         }
2683
2684         debug_print("compose_get_line_break_pos(): do_break = %d, pos = %d, col = %d\n", do_break, pos, col);
2685
2686         g_free(attrs);
2687         g_free(str);
2688
2689         *break_pos = *start;
2690         gtk_text_iter_set_line_offset(break_pos, pos);
2691
2692         return do_break;
2693 }
2694
2695 static gboolean compose_is_sig_separator(Compose *compose, GtkTextBuffer *textbuf, GtkTextIter *iter) 
2696 {
2697         char *text = NULL;
2698         GtkTextIter start = *iter;
2699         GtkTextIter end_iter;
2700         int start_pos = gtk_text_iter_get_offset(&start);
2701
2702         if (!compose->account->sig_sep)
2703                 return FALSE;
2704         
2705         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
2706                 start_pos+strlen(compose->account->sig_sep));
2707
2708         /* check sig separator */
2709         if (!strcmp(gtk_text_iter_get_text(&start, &end_iter),
2710                         compose->account->sig_sep)) {
2711                 /* check end of line (\n) */
2712                 gtk_text_buffer_get_iter_at_offset(textbuf, &start,
2713                         start_pos+strlen(compose->account->sig_sep));
2714                 gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
2715                         start_pos+strlen(compose->account->sig_sep)+1);
2716
2717                 if (!strcmp(gtk_text_iter_get_text(&start, &end_iter),"\n"));
2718                         return TRUE;
2719                 
2720
2721         }
2722
2723         return FALSE;
2724 }
2725
2726 static gboolean compose_join_next_line(Compose *compose,
2727                                        GtkTextBuffer *buffer,
2728                                        GtkTextIter *iter,
2729                                        const gchar *quote_str)
2730 {
2731         GtkTextIter iter_ = *iter, cur, prev, next, end;
2732         PangoLogAttr attrs[3];
2733         gchar *str;
2734         gchar *next_quote_str;
2735         gunichar wc1, wc2;
2736         gint quote_len;
2737         gboolean keep_cursor = FALSE;
2738
2739         if (!gtk_text_iter_forward_line(&iter_) ||
2740             gtk_text_iter_ends_line(&iter_))
2741                 return FALSE;
2742
2743         next_quote_str = compose_get_quote_str(buffer, &iter_, &quote_len);
2744
2745         if ((quote_str || next_quote_str) &&
2746             strcmp2(quote_str, next_quote_str) != 0) {
2747                 g_free(next_quote_str);
2748                 return FALSE;
2749         }
2750         g_free(next_quote_str);
2751
2752         end = iter_;
2753         if (quote_len > 0) {
2754                 gtk_text_iter_forward_chars(&end, quote_len);
2755                 if (gtk_text_iter_ends_line(&end))
2756                         return FALSE;
2757         }
2758
2759         /* don't join itemized lines */
2760         if (compose_is_itemized(buffer, &end))
2761                 return FALSE;
2762
2763         /* don't join signature separator */
2764         if (compose_is_sig_separator(compose, buffer, &iter_))
2765                 return FALSE;
2766
2767         /* delete quote str */
2768         if (quote_len > 0)
2769                 gtk_text_buffer_delete(buffer, &iter_, &end);
2770
2771         /* delete linebreak and extra spaces */
2772         prev = cur = iter_;
2773         while (gtk_text_iter_backward_char(&cur)) {
2774                 wc1 = gtk_text_iter_get_char(&cur);
2775                 if (!g_unichar_isspace(wc1))
2776                         break;
2777                 prev = cur;
2778         }
2779         next = cur = iter_;
2780         while (!gtk_text_iter_ends_line(&cur)) {
2781                 wc1 = gtk_text_iter_get_char(&cur);
2782                 if (!g_unichar_isspace(wc1))
2783                         break;
2784                 gtk_text_iter_forward_char(&cur);
2785                 next = cur;
2786         }
2787         if (!gtk_text_iter_equal(&prev, &next)) {
2788                 GtkTextMark *mark;
2789
2790                 mark = gtk_text_buffer_get_insert(buffer);
2791                 gtk_text_buffer_get_iter_at_mark(buffer, &cur, mark);
2792                 if (gtk_text_iter_equal(&prev, &cur))
2793                         keep_cursor = TRUE;
2794                 gtk_text_buffer_delete(buffer, &prev, &next);
2795         }
2796         iter_ = prev;
2797
2798         /* insert space if required */
2799         gtk_text_iter_backward_char(&prev);
2800         wc1 = gtk_text_iter_get_char(&prev);
2801         wc2 = gtk_text_iter_get_char(&next);
2802         gtk_text_iter_forward_char(&next);
2803         str = gtk_text_buffer_get_text(buffer, &prev, &next, FALSE);
2804         pango_default_break(str, -1, NULL, attrs, 3);
2805         if (!attrs[1].is_line_break ||
2806             (!g_unichar_iswide(wc1) || !g_unichar_iswide(wc2))) {
2807                 gtk_text_buffer_insert(buffer, &iter_, " ", 1);
2808                 if (keep_cursor) {
2809                         gtk_text_iter_backward_char(&iter_);
2810                         gtk_text_buffer_place_cursor(buffer, &iter_);
2811                 }
2812         }
2813         g_free(str);
2814
2815         *iter = iter_;
2816         return TRUE;
2817 }
2818
2819 static void compose_wrap_paragraph(Compose *compose, GtkTextIter *par_iter)
2820 {
2821         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2822         GtkTextBuffer *buffer;
2823         GtkTextIter iter, break_pos;
2824         gchar *quote_str = NULL;
2825         gint quote_len;
2826         gboolean wrap_quote = prefs_common.linewrap_quote;
2827         gboolean prev_autowrap = compose->autowrap;
2828
2829         compose->autowrap = FALSE;
2830
2831         buffer = gtk_text_view_get_buffer(text);
2832
2833         if (par_iter) {
2834                 iter = *par_iter;
2835         } else {
2836                 GtkTextMark *mark;
2837                 mark = gtk_text_buffer_get_insert(buffer);
2838                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2839         }
2840
2841         /* move to paragraph start */
2842         gtk_text_iter_set_line_offset(&iter, 0);
2843         if (gtk_text_iter_ends_line(&iter)) {
2844                 while (gtk_text_iter_ends_line(&iter) &&
2845                        gtk_text_iter_forward_line(&iter))
2846                         ;
2847         } else {
2848                 while (gtk_text_iter_backward_line(&iter)) {
2849                         if (gtk_text_iter_ends_line(&iter)) {
2850                                 gtk_text_iter_forward_line(&iter);
2851                                 break;
2852                         }
2853                 }
2854         }
2855
2856         /* go until paragraph end (empty line) */
2857         while (!gtk_text_iter_ends_line(&iter)) {
2858                 quote_str = compose_get_quote_str(buffer, &iter, &quote_len);
2859                 if (quote_str) {
2860                         if (!wrap_quote) {
2861                                 gtk_text_iter_forward_line(&iter);
2862                                 g_free(quote_str);
2863                                 continue;
2864                         }
2865                         debug_print("compose_wrap_paragraph(): quote_str = '%s'\n", quote_str);
2866                 }
2867
2868                 if (compose_get_line_break_pos(buffer, &iter, &break_pos,
2869                                                prefs_common.linewrap_len,
2870                                                quote_len)) {
2871                         GtkTextIter prev, next, cur;
2872
2873                         gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
2874
2875                         /* remove trailing spaces */
2876                         cur = break_pos;
2877                         gtk_text_iter_backward_char(&cur);
2878                         prev = next = cur;
2879                         while (!gtk_text_iter_starts_line(&cur)) {
2880                                 gunichar wc;
2881
2882                                 gtk_text_iter_backward_char(&cur);
2883                                 wc = gtk_text_iter_get_char(&cur);
2884                                 if (!g_unichar_isspace(wc))
2885                                         break;
2886                                 prev = cur;
2887                         }
2888                         if (!gtk_text_iter_equal(&prev, &next)) {
2889                                 gtk_text_buffer_delete(buffer, &prev, &next);
2890                                 break_pos = next;
2891                                 gtk_text_iter_forward_char(&break_pos);
2892                         }
2893
2894                         if (quote_str)
2895                                 gtk_text_buffer_insert(buffer, &break_pos,
2896                                                        quote_str, -1);
2897
2898                         iter = break_pos;
2899                         compose_join_next_line(compose, buffer, &iter, quote_str);
2900
2901                         /* move iter to current line start */
2902                         gtk_text_iter_set_line_offset(&iter, 0);
2903                 } else {
2904                         /* move iter to next line start */
2905                         iter = break_pos;
2906                         gtk_text_iter_forward_line(&iter);
2907                 }
2908
2909                 g_free(quote_str);
2910         }
2911
2912         if (par_iter)
2913                 *par_iter = iter;
2914
2915         compose->autowrap = prev_autowrap;
2916 }
2917
2918 static void compose_wrap_all(Compose *compose)
2919 {
2920         compose_wrap_all_full(compose, FALSE);
2921 }
2922
2923 static void compose_wrap_all_full(Compose *compose, gboolean autowrap)
2924 {
2925         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2926         GtkTextBuffer *buffer;
2927         GtkTextIter iter;
2928
2929         buffer = gtk_text_view_get_buffer(text);
2930
2931         gtk_text_buffer_get_start_iter(buffer, &iter);
2932         while (!gtk_text_iter_is_end(&iter))
2933                 compose_wrap_paragraph(compose, &iter);
2934 }
2935
2936 static void compose_set_title(Compose *compose)
2937 {
2938         gchar *str;
2939         gchar *edited;
2940
2941         edited = compose->modified ? _(" [Edited]") : "";
2942         if (compose->account && compose->account->address)
2943                 str = g_strdup_printf(_("%s - Compose message%s"),
2944                                       compose->account->address, edited);
2945         else
2946                 str = g_strdup_printf(_("Compose message%s"), edited);
2947         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2948         g_free(str);
2949 }
2950
2951 /**
2952  * compose_current_mail_account:
2953  * 
2954  * Find a current mail account (the currently selected account, or the
2955  * default account, if a news account is currently selected).  If a
2956  * mail account cannot be found, display an error message.
2957  * 
2958  * Return value: Mail account, or NULL if not found.
2959  **/
2960 static PrefsAccount *
2961 compose_current_mail_account(void)
2962 {
2963         PrefsAccount *ac;
2964
2965         if (cur_account && cur_account->protocol != A_NNTP)
2966                 ac = cur_account;
2967         else {
2968                 ac = account_get_default();
2969                 if (!ac || ac->protocol == A_NNTP) {
2970                         alertpanel_error(_("Account for sending mail is not specified.\n"
2971                                            "Please select a mail account before sending."));
2972                         return NULL;
2973                 }
2974         }
2975         return ac;
2976 }
2977
2978 static void compose_select_account(Compose *compose, PrefsAccount *account,
2979                                    gboolean init)
2980 {
2981         GtkItemFactory *ifactory;
2982
2983         g_return_if_fail(account != NULL);
2984
2985         compose->account = account;
2986
2987         compose_set_title(compose);
2988
2989         ifactory = gtk_item_factory_from_widget(compose->menubar);
2990 #if 0
2991         if (account->protocol == A_NNTP) {
2992                 gtk_widget_show(compose->newsgroups_hbox);
2993                 gtk_widget_show(compose->newsgroups_entry);
2994                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 4);
2995                 compose->use_newsgroups = TRUE;
2996
2997                 menu_set_active(ifactory, "/View/To", FALSE);
2998                 menu_set_sensitive(ifactory, "/View/To", TRUE);
2999                 menu_set_active(ifactory, "/View/Cc", FALSE);
3000                 menu_set_sensitive(ifactory, "/View/Cc", TRUE);
3001                 menu_set_sensitive(ifactory, "/View/Followup to", TRUE);
3002         } else {
3003                 gtk_widget_hide(compose->newsgroups_hbox);
3004                 gtk_widget_hide(compose->newsgroups_entry);
3005                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 0);
3006                 gtk_widget_queue_resize(compose->table_vbox);
3007                 compose->use_newsgroups = FALSE;
3008
3009                 menu_set_active(ifactory, "/View/To", TRUE);
3010                 menu_set_sensitive(ifactory, "/View/To", FALSE);
3011                 menu_set_active(ifactory, "/View/Cc", TRUE);
3012                 menu_set_sensitive(ifactory, "/View/Cc", FALSE);
3013                 menu_set_active(ifactory, "/View/Followup to", FALSE);
3014                 menu_set_sensitive(ifactory, "/View/Followup to", FALSE);
3015         }
3016
3017         if (account->set_autocc) {
3018                 compose_entry_show(compose, COMPOSE_ENTRY_CC);
3019                 if (account->auto_cc && compose->mode != COMPOSE_REEDIT)
3020                         compose_entry_set(compose, account->auto_cc,
3021                                           COMPOSE_ENTRY_CC);
3022         }
3023         if (account->set_autobcc) {
3024                 compose_entry_show(compose, COMPOSE_ENTRY_BCC);
3025                 if (account->auto_bcc && compose->mode != COMPOSE_REEDIT)
3026                         compose_entry_set(compose, account->auto_bcc,
3027                                           COMPOSE_ENTRY_BCC);
3028         }
3029         if (account->set_autoreplyto) {
3030                 compose_entry_show(compose, COMPOSE_ENTRY_REPLY_TO);
3031                 if (account->auto_replyto && compose->mode != COMPOSE_REEDIT)
3032                         compose_entry_set(compose, account->auto_replyto,
3033                                           COMPOSE_ENTRY_REPLY_TO);
3034         }
3035
3036 #endif
3037
3038         if (account->default_sign && compose->mode != COMPOSE_REDIRECT)
3039                 menu_set_active(ifactory, "/Options/Sign", TRUE);
3040         else
3041                 menu_set_active(ifactory, "/Options/Sign", FALSE);
3042         if (account->default_encrypt && compose->mode != COMPOSE_REDIRECT)
3043                 menu_set_active(ifactory, "/Options/Encrypt", TRUE);
3044         else
3045                 menu_set_active(ifactory, "/Options/Encrypt", FALSE);
3046                                        
3047         activate_privacy_system(compose, account);
3048
3049         if (!init && compose->mode != COMPOSE_REDIRECT)
3050                 compose_insert_sig(compose, TRUE);
3051 }
3052
3053 gboolean compose_check_for_valid_recipient(Compose *compose) {
3054         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
3055         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
3056         gboolean recipient_found = FALSE;
3057         GSList *list;
3058         gchar **strptr;
3059
3060         /* free to and newsgroup list */
3061         slist_free_strings(compose->to_list);
3062         g_slist_free(compose->to_list);
3063         compose->to_list = NULL;
3064                         
3065         slist_free_strings(compose->newsgroup_list);
3066         g_slist_free(compose->newsgroup_list);
3067         compose->newsgroup_list = NULL;
3068
3069         /* search header entries for to and newsgroup entries */
3070         for (list = compose->header_list; list; list = list->next) {
3071                 gchar *header;
3072                 gchar *entry;
3073                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3074                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3075                 g_strstrip(entry);
3076                 if (entry[0] != '\0') {
3077                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
3078                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3079                                         compose->to_list = address_list_append(compose->to_list, entry);
3080                                         recipient_found = TRUE;
3081                                 }
3082                         }
3083                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
3084                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3085                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
3086                                         recipient_found = TRUE;
3087                                 }
3088                         }
3089                 }
3090                 g_free(header);
3091                 g_free(entry);
3092         }
3093         return recipient_found;
3094 }
3095
3096 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
3097 {
3098         const gchar *str;
3099
3100         if (compose_check_for_valid_recipient(compose) == FALSE) {
3101                 alertpanel_error(_("Recipient is not specified."));
3102                 return FALSE;
3103         }
3104
3105         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3106         if (*str == '\0' && check_subject == TRUE) {
3107                 AlertValue aval;
3108
3109                 aval = alertpanel(_("Send"),
3110                                   _("Subject is empty. Send it anyway?"),
3111                                   GTK_STOCK_YES, GTK_STOCK_NO, NULL);
3112                 if (aval != G_ALERTDEFAULT)
3113                         return FALSE;
3114         }
3115
3116         return TRUE;
3117 }
3118
3119 gint compose_send(Compose *compose)
3120 {
3121         gint msgnum;
3122         FolderItem *folder;
3123         gint val = -1;
3124         gchar *msgpath;
3125
3126         compose_allow_user_actions (compose, FALSE);
3127         compose->sending = TRUE;
3128
3129         if (compose_check_entries(compose, TRUE) == FALSE)
3130                 goto bail;
3131
3132         val = compose_queue(compose, &msgnum, &folder);
3133
3134         if (val) {
3135                 alertpanel_error(_("Could not queue message for sending"));
3136                 goto bail;
3137         }
3138
3139
3140         if (prefs_common.send_dialog_mode != SEND_DIALOG_ALWAYS) {
3141                 compose->sending = FALSE;
3142                 compose_close(compose);
3143                 /* No more compose access in the normal codepath 
3144                  * after this point! */
3145         }
3146
3147         if (msgnum == 0) {
3148                 alertpanel_error(_("The message was queued but could not be "
3149                                    "sent.\nUse \"Send queued messages\" from "
3150                                    "the main window to retry."));
3151                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3152                         compose->sending = FALSE;
3153                         compose_allow_user_actions (compose, TRUE);
3154                 }
3155                 return 0;
3156         }
3157         
3158         msgpath = folder_item_fetch_msg(folder, msgnum);
3159         val = procmsg_send_message_queue(msgpath);
3160         g_free(msgpath);
3161
3162         if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3163                 compose->sending = FALSE;
3164                 compose_allow_user_actions (compose, TRUE);
3165                 if (val != 0) {
3166                         folder_item_remove_msg(folder, msgnum);
3167                         folder_item_scan(folder);
3168                 }
3169         }
3170
3171         if (val == 0) {
3172                 folder_item_remove_msg(folder, msgnum);
3173                 folder_item_scan(folder);
3174                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS)
3175                         compose_close(compose);
3176         } else {
3177                 alertpanel_error(_("The message was queued but could not be "
3178                                    "sent.\nUse \"Send queued messages\" from "
3179                                    "the main window to retry."));
3180                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3181                         compose_allow_user_actions (compose, TRUE);
3182                         compose->sending = FALSE;               
3183                 }
3184                 return -1;
3185         }
3186
3187         return 0;
3188
3189 bail:
3190         compose_allow_user_actions (compose, TRUE);
3191         compose->sending = FALSE;
3192
3193         return -1;
3194 }
3195
3196 static gboolean compose_use_attach(Compose *compose) 
3197 {
3198         GtkTreeModel *model = gtk_tree_view_get_model
3199                                 (GTK_TREE_VIEW(compose->attach_clist));
3200         return gtk_tree_model_iter_n_children(model, NULL) > 0;
3201 }
3202
3203 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3204                                                            FILE *fp)
3205 {
3206         gchar buf[BUFFSIZE];
3207         gchar *str;
3208         gboolean first_to_address;
3209         gboolean first_cc_address;
3210         GSList *list;
3211         ComposeHeaderEntry *headerentry;
3212         const gchar *headerentryname;
3213         gchar *cc_hdr;
3214         gchar *to_hdr;
3215
3216         debug_print("Writing redirect header\n");
3217
3218         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3219         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3220
3221         first_to_address = TRUE;
3222         for (list = compose->header_list; list; list = list->next) {
3223                 headerentry = ((ComposeHeaderEntry *)list->data);
3224                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3225
3226                 if (g_utf8_collate(headerentryname, to_hdr) == 0) {
3227                         const gchar *entstr = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3228                         Xstrdup_a(str, entstr, return -1);
3229                         g_strstrip(str);
3230                         if (str[0] != '\0') {
3231                                 compose_convert_header
3232                                         (buf, sizeof(buf), str,
3233                                         strlen("Resent-To") + 2, TRUE);
3234
3235                                 if (first_to_address) {
3236                                         fprintf(fp, "Resent-To: ");
3237                                         first_to_address = FALSE;
3238                                 } else {
3239                                         fprintf(fp, ",");
3240                                 }
3241                                 fprintf(fp, "%s", buf);
3242                         }
3243                 }
3244         }
3245         if (!first_to_address) {
3246                 fprintf(fp, "\n");
3247         }
3248
3249         first_cc_address = TRUE;
3250         for (list = compose->header_list; list; list = list->next) {
3251                 headerentry = ((ComposeHeaderEntry *)list->data);
3252                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3253
3254                 if (g_utf8_collate(headerentryname, cc_hdr) == 0) {
3255                         const gchar *strg = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3256                         Xstrdup_a(str, strg, return -1);
3257                         g_strstrip(str);
3258                         if (str[0] != '\0') {
3259                                 compose_convert_header
3260                                         (buf, sizeof(buf), str,
3261                                         strlen("Resent-Cc") + 2, TRUE);
3262
3263                                 if (first_cc_address) {
3264                                         fprintf(fp, "Resent-Cc: ");
3265                                         first_cc_address = FALSE;
3266                                 } else {
3267                                         fprintf(fp, ",");
3268                                 }
3269                                 fprintf(fp, "%s", buf);
3270                         }
3271                 }
3272         }
3273         if (!first_cc_address) {
3274                 fprintf(fp, "\n");
3275         }
3276         
3277         return(0);
3278 }
3279
3280 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3281 {
3282         gchar buf[BUFFSIZE];
3283         gchar *str;
3284         const gchar *entstr;
3285         /* struct utsname utsbuf; */
3286
3287         g_return_val_if_fail(fp != NULL, -1);
3288         g_return_val_if_fail(compose->account != NULL, -1);
3289         g_return_val_if_fail(compose->account->address != NULL, -1);
3290
3291         /* Resent-Date */
3292         get_rfc822_date(buf, sizeof(buf));
3293         fprintf(fp, "Resent-Date: %s\n", buf);
3294
3295         /* Resent-From */
3296         if (compose->account->name && *compose->account->name) {
3297                 compose_convert_header
3298                         (buf, sizeof(buf), compose->account->name,
3299                          strlen("From: "), TRUE);
3300                 fprintf(fp, "Resent-From: %s <%s>\n",
3301                         buf, compose->account->address);
3302         } else
3303                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3304
3305         /* Subject */
3306         entstr = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3307         if (*entstr != '\0') {
3308                 Xstrdup_a(str, entstr, return -1);
3309                 g_strstrip(str);
3310                 if (*str != '\0') {
3311                         compose_convert_header(buf, sizeof(buf), str,
3312                                                strlen("Subject: "), FALSE);
3313                         fprintf(fp, "Subject: %s\n", buf);
3314                 }
3315         }
3316
3317         /* Resent-Message-ID */
3318         if (compose->account->gen_msgid) {
3319                 generate_msgid(buf, sizeof(buf));
3320                 fprintf(fp, "Resent-Message-ID: <%s>\n", buf);
3321                 compose->msgid = g_strdup(buf);
3322         }
3323
3324         compose_redirect_write_headers_from_headerlist(compose, fp);
3325
3326         /* separator between header and body */
3327         fputs("\n", fp);
3328
3329         return 0;
3330 }
3331
3332 static gint compose_redirect_write_to_file(Compose *compose, FILE *fdest)
3333 {
3334         FILE *fp;
3335         size_t len;
3336         gchar buf[BUFFSIZE];
3337
3338         if ((fp = fopen(compose->redirect_filename, "rb")) == NULL) {
3339                 FILE_OP_ERROR(compose->redirect_filename, "fopen");
3340                 return -1;
3341         }
3342
3343         while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
3344                 /* should filter returnpath, delivered-to */
3345                 if (g_ascii_strncasecmp(buf, "Return-Path:",
3346                                         strlen("Return-Path:")) == 0 ||
3347                     g_ascii_strncasecmp(buf, "Delivered-To:",
3348                                         strlen("Delivered-To:")) == 0 ||
3349                     g_ascii_strncasecmp(buf, "Received:",
3350                                         strlen("Received:")) == 0 ||
3351                     g_ascii_strncasecmp(buf, "Subject:",
3352                                         strlen("Subject:")) == 0 ||
3353                     g_ascii_strncasecmp(buf, "X-UIDL:",
3354                                         strlen("X-UIDL:")) == 0)
3355                         continue;
3356
3357                 if (fputs(buf, fdest) == -1)
3358                         goto error;
3359
3360                 if (!prefs_common.redirect_keep_from) {
3361                         if (g_ascii_strncasecmp(buf, "From:",
3362                                           strlen("From:")) == 0) {
3363                                 fputs(" (by way of ", fdest);
3364                                 if (compose->account->name
3365                                     && *compose->account->name) {
3366                                         compose_convert_header
3367                                                 (buf, sizeof(buf),
3368                                                  compose->account->name,
3369                                                  strlen("From: "),
3370                                                  FALSE);
3371                                         fprintf(fdest, "%s <%s>",
3372                                                 buf,
3373                                                 compose->account->address);
3374                                 } else
3375                                         fprintf(fdest, "%s",
3376                                                 compose->account->address);
3377                                 fputs(")", fdest);
3378                         }
3379                 }
3380
3381                 if (fputs("\n", fdest) == -1)
3382                         goto error;
3383         }
3384
3385         compose_redirect_write_headers(compose, fdest);
3386
3387         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3388                 if (fwrite(buf, sizeof(gchar), len, fdest) != len)
3389                         goto error;
3390         }
3391
3392         fclose(fp);
3393
3394         return 0;
3395 error:
3396         fclose(fp);
3397
3398         return -1;
3399 }
3400
3401 static gint compose_write_to_file(Compose *compose, FILE *fp, gint action)
3402 {
3403         GtkTextBuffer *buffer;
3404         GtkTextIter start, end;
3405         gchar *chars;
3406         gchar *buf;
3407         const gchar *out_codeset;
3408         EncodingType encoding;
3409         MimeInfo *mimemsg, *mimetext;
3410
3411         /* create message MimeInfo */
3412         mimemsg = procmime_mimeinfo_new();
3413         mimemsg->type = MIMETYPE_MESSAGE;
3414         mimemsg->subtype = g_strdup("rfc822");
3415         mimemsg->content = MIMECONTENT_MEM;
3416         mimemsg->data.mem = compose_get_header(compose);
3417
3418         /* Create text part MimeInfo */
3419         /* get all composed text */
3420         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
3421         gtk_text_buffer_get_start_iter(buffer, &start);
3422         gtk_text_buffer_get_end_iter(buffer, &end);
3423         chars = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
3424         if (is_ascii_str(chars)) {
3425                 buf = chars;
3426                 chars = NULL;
3427                 out_codeset = CS_US_ASCII;
3428                 encoding = ENC_7BIT;
3429         } else {
3430                 const gchar *src_codeset;
3431
3432                 out_codeset = conv_get_outgoing_charset_str();
3433                 if (!g_ascii_strcasecmp(out_codeset, CS_US_ASCII))
3434                         out_codeset = CS_ISO_8859_1;
3435
3436                 if (prefs_common.encoding_method == CTE_BASE64)
3437                         encoding = ENC_BASE64;
3438                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
3439                         encoding = ENC_QUOTED_PRINTABLE;
3440                 else if (prefs_common.encoding_method == CTE_8BIT)
3441                         encoding = ENC_8BIT;
3442                 else
3443                         encoding = procmime_get_encoding_for_charset(out_codeset);
3444
3445                 src_codeset = CS_INTERNAL;
3446                 /* if current encoding is US-ASCII, set it the same as
3447                    outgoing one to prevent code conversion failure */
3448                 if (!g_ascii_strcasecmp(src_codeset, CS_US_ASCII))
3449                         src_codeset = out_codeset;
3450
3451                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
3452                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
3453
3454                 if (action == COMPOSE_WRITE_FOR_SEND) {
3455                         buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
3456                         
3457                         if (!buf) {
3458                                 AlertValue aval;
3459                                 gchar *msg;
3460
3461                                 msg = g_strdup_printf(_("Can't convert the character encoding of the message from\n"
3462                                                         "%s to %s.\n"
3463                                                         "Send it anyway?"), src_codeset, out_codeset);
3464                                 aval = alertpanel_with_type
3465                                         (_("Error"), msg, _("Yes"), _("+No"), NULL, NULL, ALERT_ERROR);
3466                                 g_free(msg);
3467
3468                                 if (aval != G_ALERTDEFAULT) {
3469                                         g_free(chars);
3470                                         return -1;
3471                                 } else {
3472                                         buf = chars;
3473                                         out_codeset = src_codeset;
3474                                         chars = NULL;
3475                                 }
3476                         }
3477                 } else {
3478                         buf = chars;
3479                         out_codeset = src_codeset;
3480                         chars = NULL;
3481                 }
3482         }
3483         g_free(chars);
3484
3485         if (encoding == ENC_8BIT || encoding == ENC_7BIT) {
3486                 if (!strncmp(buf, "From ", sizeof("From ")-1) ||
3487                     strstr(buf, "\nFrom ") != NULL) {
3488                         encoding = ENC_QUOTED_PRINTABLE;
3489                 }
3490         }
3491
3492         mimetext = procmime_mimeinfo_new();
3493         mimetext->content = MIMECONTENT_MEM;
3494         mimetext->data.mem = buf;
3495         mimetext->type = MIMETYPE_TEXT;
3496         mimetext->subtype = g_strdup("plain");
3497         g_hash_table_insert(mimetext->typeparameters, g_strdup("charset"),
3498                             g_strdup(out_codeset));
3499         /* protect trailing spaces when signing message */
3500         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
3501             privacy_system_can_sign(compose->privacy_system))
3502                 if (encoding == ENC_7BIT)
3503                         encoding = ENC_QUOTED_PRINTABLE;
3504                 else if (encoding == ENC_8BIT)
3505                         encoding = ENC_BASE64;
3506         if (encoding != ENC_UNKNOWN)
3507                 procmime_encode_content(mimetext, encoding);
3508
3509         /* append attachment parts */
3510         if (compose_use_attach(compose)) {
3511                 MimeInfo *mimempart;
3512
3513                 mimempart = procmime_mimeinfo_new();
3514                 mimempart->content = MIMECONTENT_EMPTY;
3515                 mimempart->type = MIMETYPE_MULTIPART;
3516                 mimempart->subtype = g_strdup("mixed");
3517                 g_hash_table_insert(mimempart->typeparameters, g_strdup("boundary"),
3518                                     generate_mime_boundary(NULL));
3519
3520                 mimetext->disposition = DISPOSITIONTYPE_INLINE;
3521
3522                 g_node_append(mimempart->node, mimetext->node);
3523                 g_node_append(mimemsg->node, mimempart->node);
3524
3525                 compose_add_attachments(compose, mimempart);
3526         } else
3527                 g_node_append(mimemsg->node, mimetext->node);
3528
3529         /* sign message if sending */
3530         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
3531             privacy_system_can_sign(compose->privacy_system))
3532                 if (!privacy_sign(compose->privacy_system, mimemsg, compose->account))
3533                         return -1;
3534
3535         procmime_write_mimeinfo(mimemsg, fp);
3536         
3537         procmime_mimeinfo_free_all(mimemsg);
3538
3539         return 0;
3540 }
3541
3542 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3543 {
3544         GtkTextBuffer *buffer;
3545         GtkTextIter start, end;
3546         FILE *fp;
3547         size_t len;
3548         gchar *chars, *tmp;
3549         const gchar *src_codeset, *dest_codeset;
3550
3551         if ((fp = fopen(file, "wb")) == NULL) {
3552                 FILE_OP_ERROR(file, "fopen");
3553                 return -1;
3554         }
3555
3556         /* chmod for security */
3557         if (change_file_mode_rw(fp, file) < 0) {
3558                 FILE_OP_ERROR(file, "chmod");
3559                 g_warning("can't change file mode\n");
3560         }
3561
3562         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
3563         gtk_text_buffer_get_start_iter(buffer, &start);
3564         gtk_text_buffer_get_end_iter(buffer, &end);
3565         tmp = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
3566
3567         chars = conv_codeset_strdup
3568                 (tmp, CS_INTERNAL, conv_get_locale_charset_str());
3569
3570         g_free(tmp);
3571         if (!chars) return -1;
3572
3573         /* write body */
3574         len = strlen(chars);
3575         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3576                 FILE_OP_ERROR(file, "fwrite");
3577                 g_free(chars);
3578                 fclose(fp);
3579                 unlink(file);
3580                 return -1;
3581         }
3582
3583         g_free(chars);
3584
3585         if (fclose(fp) == EOF) {
3586                 FILE_OP_ERROR(file, "fclose");
3587                 unlink(file);
3588                 return -1;
3589         }
3590         return 0;
3591 }
3592
3593 static gint compose_remove_reedit_target(Compose *compose)
3594 {
3595         FolderItem *item;
3596         MsgInfo *msginfo = compose->targetinfo;
3597
3598         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3599         if (!msginfo) return -1;
3600
3601         item = msginfo->folder;
3602         g_return_val_if_fail(item != NULL, -1);
3603
3604         if (procmsg_msg_exist(msginfo) &&
3605             (item->stype == F_DRAFT || item->stype == F_QUEUE 
3606              || msginfo == compose->autosaved_draft)) {
3607                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3608                         g_warning("can't remove the old message\n");
3609                         return -1;
3610                 }
3611         }
3612
3613         return 0;
3614 }
3615
3616 void compose_remove_draft(Compose *compose)
3617 {
3618         FolderItem *drafts;
3619         MsgInfo *msginfo = compose->targetinfo;
3620         drafts = account_get_special_folder(compose->account, F_DRAFT);
3621
3622         if (procmsg_msg_exist(msginfo)) {
3623                 folder_item_remove_msg(drafts, msginfo->msgnum);
3624         }
3625
3626 }
3627
3628 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3629 {
3630         return compose_queue_sub (compose, msgnum, item, FALSE);
3631 }
3632 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
3633 {
3634         FolderItem *queue;
3635         gchar *tmp;
3636         FILE *fp;
3637         GSList *cur;
3638         gint num;
3639         static gboolean lock = FALSE;
3640         PrefsAccount *mailac = NULL, *newsac = NULL;
3641         
3642         debug_print("queueing message...\n");
3643         g_return_val_if_fail(compose->account != NULL, -1);
3644
3645         lock = TRUE;
3646         
3647         if (compose_check_entries(compose, check_subject) == FALSE) {
3648                 lock = FALSE;
3649                 return -1;
3650         }
3651
3652         if (!compose->to_list && !compose->newsgroup_list) {
3653                 g_warning("can't get recipient list.");
3654                 lock = FALSE;
3655                 return -1;
3656         }
3657
3658         if (compose->to_list) {
3659                 if (compose->account->protocol != A_NNTP)
3660                         mailac = compose->account;
3661                 else if (cur_account && cur_account->protocol != A_NNTP)
3662                         mailac = cur_account;
3663                 else if (!(mailac = compose_current_mail_account())) {
3664                         lock = FALSE;
3665                         alertpanel_error(_("No account for sending mails available!"));
3666                         return -1;
3667                 }
3668         }
3669
3670         if (compose->newsgroup_list) {
3671                 if (compose->account->protocol == A_NNTP)
3672                         newsac = compose->account;
3673                 else if (!newsac->protocol != A_NNTP) {
3674                         lock = FALSE;
3675                         alertpanel_error(_("No account for posting news available!"));
3676                         return -1;
3677                 }                       
3678         }
3679
3680         if (prefs_common.linewrap_at_send)
3681                 compose_wrap_all(compose);
3682
3683         /* write queue header */
3684         tmp = g_strdup_printf("%s%cqueue.%p", get_tmp_dir(),
3685                               G_DIR_SEPARATOR, compose);
3686         if ((fp = fopen(tmp, "wb")) == NULL) {
3687                 FILE_OP_ERROR(tmp, "fopen");
3688                 g_free(tmp);
3689                 return -1;
3690         }
3691
3692         if (change_file_mode_rw(fp, tmp) < 0) {
3693                 FILE_OP_ERROR(tmp, "chmod");
3694                 g_warning("can't change file mode\n");
3695         }
3696
3697         /* queueing variables */
3698         fprintf(fp, "AF:\n");
3699         fprintf(fp, "NF:0\n");
3700         fprintf(fp, "PS:10\n");
3701         fprintf(fp, "SRH:1\n");
3702         fprintf(fp, "SFN:\n");
3703         fprintf(fp, "DSR:\n");
3704         if (compose->msgid)
3705                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3706         else
3707                 fprintf(fp, "MID:\n");
3708         fprintf(fp, "CFG:\n");
3709         fprintf(fp, "PT:0\n");
3710         fprintf(fp, "S:%s\n", compose->account->address);
3711         fprintf(fp, "RQ:\n");
3712         if (mailac)
3713                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3714         else
3715                 fprintf(fp, "SSV:\n");
3716         if (newsac)
3717                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3718         else
3719                 fprintf(fp, "NSV:\n");
3720         fprintf(fp, "SSH:\n");
3721         /* write recepient list */
3722         if (compose->to_list) {
3723                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
3724                 for (cur = compose->to_list->next; cur != NULL;
3725                      cur = cur->next)
3726                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3727                 fprintf(fp, "\n");
3728         }
3729         /* write newsgroup list */
3730         if (compose->newsgroup_list) {
3731                 fprintf(fp, "NG:");
3732                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3733                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3734                         fprintf(fp, ",%s", (gchar *)cur->data);
3735                 fprintf(fp, "\n");
3736         }
3737         /* Sylpheed account IDs */
3738         if (mailac)
3739                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3740         if (newsac)
3741                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3742
3743         if (compose->privacy_system != NULL) {
3744                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
3745                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
3746                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
3747                 if (compose->use_encryption) {
3748                         gchar *encdata;
3749
3750                         encdata = privacy_get_encrypt_data(compose->privacy_system, compose->to_list);
3751                         if (encdata != NULL)
3752                                 fprintf(fp, "X-Sylpheed-Encrypt-Data:%s\n", 
3753                                         encdata);
3754                         g_free(encdata);
3755                 }
3756         }
3757
3758         /* Save copy folder */
3759         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3760                 gchar *savefolderid;
3761                 
3762                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3763                 fprintf(fp, "SCF:%s\n", savefolderid);
3764                 g_free(savefolderid);
3765         }
3766         /* Message-ID of message replying to */
3767         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
3768                 gchar *folderid;
3769                 
3770                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
3771                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
3772                 g_free(folderid);
3773         }
3774         /* Message-ID of message forwarding to */
3775         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
3776                 gchar *folderid;
3777                 
3778                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
3779                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
3780                 g_free(folderid);
3781         }
3782         fprintf(fp, "\n");
3783
3784         if (compose->redirect_filename != NULL) {
3785                 if (compose_redirect_write_to_file(compose, fp) < 0) {
3786                         lock = FALSE;
3787                         fclose(fp);
3788                         unlink(tmp);
3789                         g_free(tmp);
3790      &n