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