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