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