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