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