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