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