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