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