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