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