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