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