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