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