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