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