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