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