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