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