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