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