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