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