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