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