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