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