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