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