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