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