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