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