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