2006-02-24 [wwp] 2.0.0cvs80
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
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 #ifndef G_OS_WIN32  /* fixme we should have a configure test. */
76 #include <libgen.h>
77 #endif
78
79 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
80 #  include <wchar.h>
81 #  include <wctype.h>
82 #endif
83
84 #include "sylpheed.h"
85 #include "main.h"
86 #include "mainwindow.h"
87 #include "compose.h"
88 #include "addressbook.h"
89 #include "folderview.h"
90 #include "procmsg.h"
91 #include "menu.h"
92 #include "stock_pixmap.h"
93 #include "send_message.h"
94 #include "imap.h"
95 #include "news.h"
96 #include "customheader.h"
97 #include "prefs_common.h"
98 #include "prefs_account.h"
99 #include "action.h"
100 #include "account.h"
101 #include "filesel.h"
102 #include "procheader.h"
103 #include "procmime.h"
104 #include "statusbar.h"
105 #include "about.h"
106 #include "base64.h"
107 #include "quoted-printable.h"
108 #include "codeconv.h"
109 #include "utils.h"
110 #include "gtkutils.h"
111 #include "socket.h"
112 #include "alertpanel.h"
113 #include "manage_window.h"
114 #include "gtkshruler.h"
115 #include "folder.h"
116 #include "addr_compl.h"
117 #include "quote_fmt.h"
118 #include "undo.h"
119 #include "foldersel.h"
120 #include "toolbar.h"
121 #include "inc.h"
122 #include "message_search.h"
123
124 enum
125 {
126         COL_MIMETYPE = 0,
127         COL_SIZE     = 1,
128         COL_NAME     = 2,
129         COL_DATA     = 3,
130         COL_AUTODATA = 4,
131         N_COL_COLUMNS
132 };
133
134 #define N_ATTACH_COLS   (N_COL_COLUMNS)
135
136 typedef enum
137 {
138         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
139         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
140         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
141         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
142         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
143         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
144         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
145         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
146         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
147         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
148         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
149         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
150         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
151         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
152         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END
153 } ComposeCallAdvancedAction;
154
155 typedef enum
156 {
157         PRIORITY_HIGHEST = 1,
158         PRIORITY_HIGH,
159         PRIORITY_NORMAL,
160         PRIORITY_LOW,
161         PRIORITY_LOWEST
162 } PriorityLevel;
163
164 typedef enum
165 {
166         COMPOSE_INSERT_SUCCESS,
167         COMPOSE_INSERT_READ_ERROR,
168         COMPOSE_INSERT_INVALID_CHARACTER,
169         COMPOSE_INSERT_NO_FILE
170 } ComposeInsertResult;
171
172 typedef enum
173 {
174         COMPOSE_QUIT_EDITING,
175         COMPOSE_KEEP_EDITING,
176         COMPOSE_AUTO_SAVE
177 } ComposeDraftAction;
178
179 typedef enum
180 {
181         COMPOSE_WRITE_FOR_SEND,
182         COMPOSE_WRITE_FOR_STORE
183 } ComposeWriteType;
184
185 #define B64_LINE_SIZE           57
186 #define B64_BUFFSIZE            77
187
188 #define MAX_REFERENCES_LEN      999
189
190 static GList *compose_list = NULL;
191
192 Compose *compose_generic_new                    (PrefsAccount   *account,
193                                                  const gchar    *to,
194                                                  FolderItem     *item,
195                                                  GPtrArray      *attach_files,
196                                                  GList          *listAddress );
197
198 static Compose *compose_create                  (PrefsAccount   *account,
199                                                  ComposeMode     mode);
200
201 static GtkWidget *compose_account_option_menu_create
202                                                 (Compose        *compose);
203 static void compose_set_out_encoding            (Compose        *compose);
204 static void compose_set_template_menu           (Compose        *compose);
205 static void compose_template_apply              (Compose        *compose,
206                                                  Template       *tmpl,
207                                                  gboolean        replace);
208 static void compose_destroy                     (Compose        *compose);
209
210 static void compose_entries_set                 (Compose        *compose,
211                                                  const gchar    *mailto);
212 static gint compose_parse_header                (Compose        *compose,
213                                                  MsgInfo        *msginfo);
214 static gchar *compose_parse_references          (const gchar    *ref,
215                                                  const gchar    *msgid);
216
217 static gchar *compose_quote_fmt                 (Compose        *compose,
218                                                  MsgInfo        *msginfo,
219                                                  const gchar    *fmt,
220                                                  const gchar    *qmark,
221                                                  const gchar    *body,
222                                                  gboolean        rewrap);
223
224 static void compose_reply_set_entry             (Compose        *compose,
225                                                  MsgInfo        *msginfo,
226                                                  gboolean        to_all,
227                                                  gboolean        to_ml,
228                                                  gboolean        to_sender,
229                                                  gboolean
230                                                  followup_and_reply_to);
231 static void compose_reedit_set_entry            (Compose        *compose,
232                                                  MsgInfo        *msginfo);
233
234 static void compose_insert_sig                  (Compose        *compose,
235                                                  gboolean        replace);
236 static gchar *compose_get_signature_str         (Compose        *compose);
237 static ComposeInsertResult compose_insert_file  (Compose        *compose,
238                                                  const gchar    *file);
239
240 static void compose_attach_append               (Compose        *compose,
241                                                  const gchar    *file,
242                                                  const gchar    *type,
243                                                  const gchar    *content_type);
244 static void compose_attach_parts                (Compose        *compose,
245                                                  MsgInfo        *msginfo);
246
247 static void compose_beautify_paragraph          (Compose        *compose,
248                                                  GtkTextIter    *par_iter,
249                                                  gboolean        force);
250 static void compose_wrap_all                    (Compose        *compose);
251 static void compose_wrap_all_full               (Compose        *compose,
252                                                  gboolean        autowrap);
253
254 static void compose_set_title                   (Compose        *compose);
255 static void compose_select_account              (Compose        *compose,
256                                                  PrefsAccount   *account,
257                                                  gboolean        init);
258
259 static PrefsAccount *compose_current_mail_account(void);
260 /* static gint compose_send                     (Compose        *compose); */
261 static gboolean compose_check_for_valid_recipient
262                                                 (Compose        *compose);
263 static gboolean compose_check_entries           (Compose        *compose,
264                                                  gboolean       check_subject);
265 static gint compose_write_to_file               (Compose        *compose,
266                                                  FILE           *fp,
267                                                  gint            action);
268 static gint compose_write_body_to_file          (Compose        *compose,
269                                                  const gchar    *file);
270 static gint compose_remove_reedit_target        (Compose        *compose,
271                                                  gboolean        force);
272 void compose_remove_draft                       (Compose        *compose);
273 static gint compose_queue                       (Compose        *compose,
274                                                  gint           *msgnum,
275                                                  FolderItem     **item,
276                                                  gchar          **msgpath);
277 static gint compose_queue_sub                   (Compose        *compose,
278                                                  gint           *msgnum,
279                                                  FolderItem     **item,
280                                                  gchar          **msgpath,
281                                                  gboolean       check_subject);
282 static void compose_add_attachments             (Compose        *compose,
283                                                  MimeInfo       *parent);
284 static gchar *compose_get_header                (Compose        *compose);
285
286 static void compose_convert_header              (Compose        *compose,
287                                                  gchar          *dest,
288                                                  gint            len,
289                                                  gchar          *src,
290                                                  gint            header_len,
291                                                  gboolean        addr_field);
292
293 static void compose_attach_info_free            (AttachInfo     *ainfo);
294 static void compose_attach_remove_selected      (Compose        *compose);
295
296 static void compose_attach_property             (Compose        *compose);
297 static void compose_attach_property_create      (gboolean       *cancelled);
298 static void attach_property_ok                  (GtkWidget      *widget,
299                                                  gboolean       *cancelled);
300 static void attach_property_cancel              (GtkWidget      *widget,
301                                                  gboolean       *cancelled);
302 static gint attach_property_delete_event        (GtkWidget      *widget,
303                                                  GdkEventAny    *event,
304                                                  gboolean       *cancelled);
305 static gboolean attach_property_key_pressed     (GtkWidget      *widget,
306                                                  GdkEventKey    *event,
307                                                  gboolean       *cancelled);
308
309 static void compose_exec_ext_editor             (Compose        *compose);
310 #ifdef G_OS_UNIX
311 static gint compose_exec_ext_editor_real        (const gchar    *file);
312 static gboolean compose_ext_editor_kill         (Compose        *compose);
313 static gboolean compose_input_cb                (GIOChannel     *source,
314                                                  GIOCondition    condition,
315                                                  gpointer        data);
316 static void compose_set_ext_editor_sensitive    (Compose        *compose,
317                                                  gboolean        sensitive);
318 #endif /* G_OS_UNIX */
319
320 static void compose_undo_state_changed          (UndoMain       *undostruct,
321                                                  gint            undo_state,
322                                                  gint            redo_state,
323                                                  gpointer        data);
324
325 static void compose_create_header_entry (Compose *compose);
326 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
327 static void compose_update_priority_menu_item(Compose * compose);
328
329 static void compose_add_field_list      ( Compose *compose,
330                                           GList *listAddress );
331
332 /* callback functions */
333
334 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
335                                          GtkAllocation  *allocation,
336                                          GtkSHRuler     *shruler);
337 static void account_activated           (GtkMenuItem    *menuitem,
338                                          gpointer        data);
339 static void attach_selected             (GtkTreeView    *tree_view, 
340                                          GtkTreePath    *tree_path,
341                                          GtkTreeViewColumn *column, 
342                                          Compose *compose);
343 static gboolean attach_button_pressed   (GtkWidget      *widget,
344                                          GdkEventButton *event,
345                                          gpointer        data);
346 static gboolean attach_key_pressed      (GtkWidget      *widget,
347                                          GdkEventKey    *event,
348                                          gpointer        data);
349
350 static void compose_send_cb             (gpointer        data,
351                                          guint           action,
352                                          GtkWidget      *widget);
353 static void compose_send_later_cb       (gpointer        data,
354                                          guint           action,
355                                          GtkWidget      *widget);
356
357 static void compose_draft_cb            (gpointer        data,
358                                          guint           action,
359                                          GtkWidget      *widget);
360
361 static void compose_attach_cb           (gpointer        data,
362                                          guint           action,
363                                          GtkWidget      *widget);
364 static void compose_insert_file_cb      (gpointer        data,
365                                          guint           action,
366                                          GtkWidget      *widget);
367 static void compose_insert_sig_cb       (gpointer        data,
368                                          guint           action,
369                                          GtkWidget      *widget);
370
371 static void compose_close_cb            (gpointer        data,
372                                          guint           action,
373                                          GtkWidget      *widget);
374
375 static void compose_set_encoding_cb     (gpointer        data,
376                                          guint           action,
377                                          GtkWidget      *widget);
378
379 static void compose_address_cb          (gpointer        data,
380                                          guint           action,
381                                          GtkWidget      *widget);
382 static void compose_template_activate_cb(GtkWidget      *widget,
383                                          gpointer        data);
384
385 static void compose_ext_editor_cb       (gpointer        data,
386                                          guint           action,
387                                          GtkWidget      *widget);
388
389 static gint compose_delete_cb           (GtkWidget      *widget,
390                                          GdkEventAny    *event,
391                                          gpointer        data);
392
393 static void compose_undo_cb             (Compose        *compose);
394 static void compose_redo_cb             (Compose        *compose);
395 static void compose_cut_cb              (Compose        *compose);
396 static void compose_copy_cb             (Compose        *compose);
397 static void compose_paste_cb            (Compose        *compose);
398 static void compose_paste_as_quote_cb   (Compose        *compose);
399 static void compose_paste_no_wrap_cb    (Compose        *compose);
400 static void compose_paste_wrap_cb       (Compose        *compose);
401 static void compose_allsel_cb           (Compose        *compose);
402
403 static void compose_advanced_action_cb  (Compose                   *compose,
404                                          ComposeCallAdvancedAction  action);
405
406 static void compose_grab_focus_cb       (GtkWidget      *widget,
407                                          Compose        *compose);
408
409 static void compose_changed_cb          (GtkTextBuffer  *textbuf,
410                                          Compose        *compose);
411
412 static void compose_wrap_cb             (gpointer        data,
413                                          guint           action,
414                                          GtkWidget      *widget);
415 static void compose_find_cb             (gpointer        data,
416                                          guint           action,
417                                          GtkWidget      *widget);
418 static void compose_toggle_autowrap_cb  (gpointer        data,
419                                          guint           action,
420                                          GtkWidget      *widget);
421
422 static void compose_toggle_ruler_cb     (gpointer        data,
423                                          guint           action,
424                                          GtkWidget      *widget);
425 static void compose_toggle_sign_cb      (gpointer        data,
426                                          guint           action,
427                                          GtkWidget      *widget);
428 static void compose_toggle_encrypt_cb   (gpointer        data,
429                                          guint           action,
430                                          GtkWidget      *widget);
431 static void compose_set_privacy_system_cb(GtkWidget      *widget,
432                                           gpointer        data);
433 static void compose_update_privacy_system_menu_item(Compose * compose, gboolean warn);
434 static void activate_privacy_system     (Compose *compose, 
435                                          PrefsAccount *account,
436                                          gboolean warn);
437 static void compose_use_signing(Compose *compose, gboolean use_signing);
438 static void compose_use_encryption(Compose *compose, gboolean use_encryption);
439 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
440                                              GtkWidget *widget);
441 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
442                                              GtkWidget *widget);
443 static void compose_set_priority_cb     (gpointer        data,
444                                          guint           action,
445                                          GtkWidget      *widget);
446
447 static void compose_attach_drag_received_cb (GtkWidget          *widget,
448                                              GdkDragContext     *drag_context,
449                                              gint                x,
450                                              gint                y,
451                                              GtkSelectionData   *data,
452                                              guint               info,
453                                              guint               time,
454                                              gpointer            user_data);
455 static void compose_insert_drag_received_cb (GtkWidget          *widget,
456                                              GdkDragContext     *drag_context,
457                                              gint                x,
458                                              gint                y,
459                                              GtkSelectionData   *data,
460                                              guint               info,
461                                              guint               time,
462                                              gpointer            user_data);
463 static void compose_header_drag_received_cb (GtkWidget          *widget,
464                                              GdkDragContext     *drag_context,
465                                              gint                x,
466                                              gint                y,
467                                              GtkSelectionData   *data,
468                                              guint               info,
469                                              guint               time,
470                                              gpointer            user_data);
471
472 static gboolean compose_drag_drop           (GtkWidget *widget,
473                                              GdkDragContext *drag_context,
474                                              gint x, gint y,
475                                              guint time, gpointer user_data);
476
477 static void text_inserted               (GtkTextBuffer  *buffer,
478                                          GtkTextIter    *iter,
479                                          const gchar    *text,
480                                          gint            len,
481                                          Compose        *compose);
482 static Compose *compose_generic_reply(MsgInfo *msginfo, gboolean quote,
483                                   gboolean to_all, gboolean to_ml,
484                                   gboolean to_sender,
485                                   gboolean followup_and_reply_to,
486                                   const gchar *body);
487
488 gboolean compose_headerentry_changed_cb    (GtkWidget          *entry,
489                                             ComposeHeaderEntry *headerentry);
490 gboolean compose_headerentry_key_press_event_cb(GtkWidget              *entry,
491                                             GdkEventKey        *event,
492                                             ComposeHeaderEntry *headerentry);
493
494 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
495
496 static void compose_allow_user_actions (Compose *compose, gboolean allow);
497
498 #if USE_ASPELL
499 static void compose_check_all              (Compose *compose);
500 static void compose_highlight_all          (Compose *compose);
501 static void compose_check_backwards        (Compose *compose);
502 static void compose_check_forwards_go      (Compose *compose);
503 #endif
504
505 static gint compose_defer_auto_save_draft       (Compose        *compose);
506 static PrefsAccount *compose_guess_forward_account_from_msginfo (MsgInfo *msginfo);
507
508 static gboolean compose_close   (Compose *compose);
509
510 static GtkItemFactoryEntry compose_popup_entries[] =
511 {
512         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
513         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
514         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
515         {N_("/_Properties..."), NULL, compose_attach_property, 0, NULL}
516 };
517
518 static GtkItemFactoryEntry compose_entries[] =
519 {
520         {N_("/_Message"),                               NULL, NULL, 0, "<Branch>"},
521         {N_("/_Message/_Send"),         "<control>Return",
522                                         compose_send_cb, 0, NULL},
523         {N_("/_Message/Send _later"),   "<shift><control>S",
524                                         compose_send_later_cb,  0, NULL},
525         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
526         {N_("/_Message/_Attach file"),          "<control>M", compose_attach_cb,      0, NULL},
527         {N_("/_Message/_Insert file"),          "<control>I", compose_insert_file_cb, 0, NULL},
528         {N_("/_Message/Insert si_gnature"),     "<control>G", compose_insert_sig_cb,  0, NULL},
529         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
530         {N_("/_Message/_Save"),
531                                                 "<control>S", compose_draft_cb, COMPOSE_KEEP_EDITING, NULL},
532         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
533         {N_("/_Message/_Close"),                        "<control>W", compose_close_cb, 0, NULL},
534
535         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
536         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
537         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
538         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
539         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
540         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
541         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
542         {N_("/_Edit/Special paste"),    NULL, NULL, 0, "<Branch>"},
543         {N_("/_Edit/Special paste/as _quotation"),
544                                         NULL, compose_paste_as_quote_cb, 0, NULL},
545         {N_("/_Edit/Special paste/_wrapped"),
546                                         NULL, compose_paste_wrap_cb, 0, NULL},
547         {N_("/_Edit/Special paste/_unwrapped"),
548                                         NULL, compose_paste_no_wrap_cb, 0, NULL},
549         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
550         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
551         {N_("/_Edit/A_dvanced/Move a character backward"),
552                                         "<shift><control>B",
553                                         compose_advanced_action_cb,
554                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
555                                         NULL},
556         {N_("/_Edit/A_dvanced/Move a character forward"),
557                                         "<shift><control>F",
558                                         compose_advanced_action_cb,
559                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
560                                         NULL},
561         {N_("/_Edit/A_dvanced/Move a word backward"),
562                                         NULL, /* "<alt>B" */
563                                         compose_advanced_action_cb,
564                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
565                                         NULL},
566         {N_("/_Edit/A_dvanced/Move a word forward"),
567                                         NULL, /* "<alt>F" */
568                                         compose_advanced_action_cb,
569                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
570                                         NULL},
571         {N_("/_Edit/A_dvanced/Move to beginning of line"),
572                                         NULL, /* "<control>A" */
573                                         compose_advanced_action_cb,
574                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
575                                         NULL},
576         {N_("/_Edit/A_dvanced/Move to end of line"),
577                                         "<control>E",
578                                         compose_advanced_action_cb,
579                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
580                                         NULL},
581         {N_("/_Edit/A_dvanced/Move to previous line"),
582                                         "<control>P",
583                                         compose_advanced_action_cb,
584                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
585                                         NULL},
586         {N_("/_Edit/A_dvanced/Move to next line"),
587                                         "<control>N",
588                                         compose_advanced_action_cb,
589                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
590                                         NULL},
591         {N_("/_Edit/A_dvanced/Delete a character backward"),
592                                         "<control>H",
593                                         compose_advanced_action_cb,
594                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
595                                         NULL},
596         {N_("/_Edit/A_dvanced/Delete a character forward"),
597                                         "<control>D",
598                                         compose_advanced_action_cb,
599                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
600                                         NULL},
601         {N_("/_Edit/A_dvanced/Delete a word backward"),
602                                         NULL, /* "<control>W" */
603                                         compose_advanced_action_cb,
604                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
605                                         NULL},
606         {N_("/_Edit/A_dvanced/Delete a word forward"),
607                                         NULL, /* "<alt>D", */
608                                         compose_advanced_action_cb,
609                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
610                                         NULL},
611         {N_("/_Edit/A_dvanced/Delete line"),
612                                         "<control>U",
613                                         compose_advanced_action_cb,
614                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
615                                         NULL},
616         {N_("/_Edit/A_dvanced/Delete entire line"),
617                                         NULL,
618                                         compose_advanced_action_cb,
619                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
620                                         NULL},
621         {N_("/_Edit/A_dvanced/Delete to end of line"),
622                                         "<control>K",
623                                         compose_advanced_action_cb,
624                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END,
625                                         NULL},
626         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
627         {N_("/_Edit/_Find"),
628                                         "<control>F", compose_find_cb, 0, NULL},
629         {N_("/_Edit/---"),                      NULL, NULL, 0, "<Separator>"},
630         {N_("/_Edit/_Wrap current paragraph"),
631                                         "<control>L", compose_wrap_cb, 0, NULL},
632         {N_("/_Edit/Wrap all long _lines"),
633                                         "<control><alt>L", compose_wrap_cb, 1, NULL},
634         {N_("/_Edit/Aut_o wrapping"),   "<shift><control>L", compose_toggle_autowrap_cb, 0, "<ToggleItem>"},
635         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
636         {N_("/_Edit/Edit with e_xternal editor"),
637                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
638 #if USE_ASPELL
639         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
640         {N_("/_Spelling/_Check all or check selection"),
641                                         NULL, compose_check_all, 0, NULL},
642         {N_("/_Spelling/_Highlight all misspelled words"),
643                                         NULL, compose_highlight_all, 0, NULL},
644         {N_("/_Spelling/Check _backwards misspelled word"),
645                                         NULL, compose_check_backwards , 0, NULL},
646         {N_("/_Spelling/_Forward to next misspelled word"),
647                                         NULL, compose_check_forwards_go, 0, NULL},
648 #endif
649         {N_("/_Options"),               NULL, NULL, 0, "<Branch>"},
650         {N_("/_Options/Privacy System"),                NULL, NULL,   0, "<Branch>"},
651         {N_("/_Options/Privacy System/None"),   NULL, NULL,   0, "<RadioItem>"},
652         {N_("/_Options/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
653         {N_("/_Options/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
654         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
655         {N_("/_Options/_Priority"),     NULL,           NULL,   0, "<Branch>"},
656         {N_("/_Options/Priority/_Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
657         {N_("/_Options/Priority/Hi_gh"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Options/Priority/Highest"},
658         {N_("/_Options/Priority/_Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Options/Priority/Highest"},
659         {N_("/_Options/Priority/Lo_w"),    NULL, compose_set_priority_cb, PRIORITY_LOW, "/Options/Priority/Highest"},
660         {N_("/_Options/Priority/_Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Options/Priority/Highest"},
661         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
662         {N_("/_Options/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
663         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
664         {N_("/_Options/Remo_ve references"),    NULL, compose_toggle_remove_refs_cb, 0, "<ToggleItem>"},
665         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
666
667 #define ENC_ACTION(action) \
668         NULL, compose_set_encoding_cb, action, \
669         "/Options/Character encoding/Automatic"
670
671         {N_("/_Options/Character _encoding"), NULL, NULL, 0, "<Branch>"},
672         {N_("/_Options/Character _encoding/_Automatic"),
673                         NULL, compose_set_encoding_cb, C_AUTO, "<RadioItem>"},
674         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
675
676         {N_("/_Options/Character _encoding/7bit ascii (US-ASC_II)"),
677          ENC_ACTION(C_US_ASCII)},
678         {N_("/_Options/Character _encoding/Unicode (_UTF-8)"),
679          ENC_ACTION(C_UTF_8)},
680         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
681
682         {N_("/_Options/Character _encoding/Western European (ISO-8859-_1)"),
683          ENC_ACTION(C_ISO_8859_1)},
684         {N_("/_Options/Character _encoding/Western European (ISO-8859-15)"),
685          ENC_ACTION(C_ISO_8859_15)},
686         {N_("/_Options/Character _encoding/Western European (Windows-1252)"),
687          ENC_ACTION(C_WINDOWS_1252)},
688         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
689
690         {N_("/_Options/Character _encoding/Central European (ISO-8859-_2)"),
691          ENC_ACTION(C_ISO_8859_2)},
692         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
693
694         {N_("/_Options/Character _encoding/_Baltic (ISO-8859-13)"),
695          ENC_ACTION(C_ISO_8859_13)},
696         {N_("/_Options/Character _encoding/Baltic (ISO-8859-_4)"),
697          ENC_ACTION(C_ISO_8859_4)},
698         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
699
700         {N_("/_Options/Character _encoding/Greek (ISO-8859-_7)"),
701          ENC_ACTION(C_ISO_8859_7)},
702         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
703
704         {N_("/_Options/Character _encoding/Hebrew (ISO-8859-_8)"),
705          ENC_ACTION(C_ISO_8859_8)},
706         {N_("/_Options/Character _encoding/Hebrew (Windows-1255)"),
707          ENC_ACTION(C_WINDOWS_1255)},
708         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
709
710         {N_("/_Options/Character _encoding/Arabic (ISO-8859-_6)"),
711          ENC_ACTION(C_ISO_8859_6)},
712         {N_("/_Options/Character _encoding/Arabic (Windows-1256)"),
713          ENC_ACTION(C_CP1256)},
714         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
715
716         {N_("/_Options/Character _encoding/Turkish (ISO-8859-_9)"),
717          ENC_ACTION(C_ISO_8859_9)},
718         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
719
720         {N_("/_Options/Character _encoding/Cyrillic (ISO-8859-_5)"),
721          ENC_ACTION(C_ISO_8859_5)},
722         {N_("/_Options/Character _encoding/Cyrillic (KOI8-_R)"),
723          ENC_ACTION(C_KOI8_R)},
724         {N_("/_Options/Character _encoding/Cyrillic (KOI8-U)"),
725          ENC_ACTION(C_KOI8_U)},
726         {N_("/_Options/Character _encoding/Cyrillic (Windows-1251)"),
727          ENC_ACTION(C_WINDOWS_1251)},
728         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
729
730         {N_("/_Options/Character _encoding/Japanese (ISO-2022-_JP)"),
731          ENC_ACTION(C_ISO_2022_JP)},
732         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
733
734         {N_("/_Options/Character _encoding/Simplified Chinese (_GB2312)"),
735          ENC_ACTION(C_GB2312)},
736         {N_("/_Options/Character _encoding/Simplified Chinese (GBK)"),
737          ENC_ACTION(C_GBK)},
738         {N_("/_Options/Character _encoding/Traditional Chinese (_Big5)"),
739          ENC_ACTION(C_BIG5)},
740         {N_("/_Options/Character _encoding/Traditional Chinese (EUC-_TW)"),
741          ENC_ACTION(C_EUC_TW)},
742         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
743
744         {N_("/_Options/Character _encoding/Korean (EUC-_KR)"),
745          ENC_ACTION(C_EUC_KR)},
746         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
747
748         {N_("/_Options/Character _encoding/Thai (TIS-620)"),
749          ENC_ACTION(C_TIS_620)},
750         {N_("/_Options/Character _encoding/Thai (Windows-874)"),
751          ENC_ACTION(C_WINDOWS_874)},
752
753         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
754         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
755         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
756         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
757         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
758         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
759         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
760 };
761
762 static GtkTargetEntry compose_mime_types[] =
763 {
764         {"text/uri-list", 0, 0},
765         {"text/plain", 0, 0},
766         {"STRING", 0, 0}
767 };
768
769 static gboolean compose_put_existing_to_front(MsgInfo *info)
770 {
771         GList *compose_list = compose_get_compose_list();
772         GList *elem = NULL;
773         
774         if (compose_list) {
775                 for (elem = compose_list; elem != NULL && elem->data != NULL; 
776                      elem = elem->next) {
777                         Compose *c = (Compose*)elem->data;
778
779                         if (!c->targetinfo || !c->targetinfo->msgid ||
780                             !info->msgid)
781                                 continue;
782
783                         if (!strcmp(c->targetinfo->msgid, info->msgid)) {
784                                 gtkut_window_popup(c->window);
785                                 return TRUE;
786                         }
787                 }
788         }
789         return FALSE;
790 }
791
792 static GdkColor quote_color = 
793         {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
794
795 static GdkColor signature_color = {
796         (gulong)0,
797         (gushort)0x7fff,
798         (gushort)0x7fff,
799         (gushort)0x7fff
800 };
801
802 static GdkColor uri_color = {
803         (gulong)0,
804         (gushort)0,
805         (gushort)0,
806         (gushort)0
807 };
808
809 static void compose_create_tags(GtkTextView *text, Compose *compose)
810 {
811         GtkTextBuffer *buffer;
812         GdkColor black = {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
813
814         buffer = gtk_text_view_get_buffer(text);
815         
816         if (prefs_common.enable_color) {
817                 /* grab the quote colors, converting from an int to a GdkColor */
818                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
819                                                &quote_color);
820                 gtkut_convert_int_to_gdk_color(prefs_common.signature_col,
821                                                &signature_color);
822                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
823                                                &uri_color);
824         } else {
825                 signature_color = quote_color = uri_color = black;
826         }
827
828         gtk_text_buffer_create_tag(buffer, "quote",
829                                    "foreground-gdk", &quote_color,
830                                    NULL);
831         gtk_text_buffer_create_tag(buffer, "signature",
832                                    "foreground-gdk", &signature_color,
833                                    NULL);
834         gtk_text_buffer_create_tag(buffer, "link",
835                                          "foreground-gdk", &uri_color,
836                                          NULL);
837         compose->no_wrap_tag = gtk_text_buffer_create_tag(buffer, "no_wrap", NULL);
838         compose->no_join_tag = gtk_text_buffer_create_tag(buffer, "no_join", NULL);
839 }
840
841 Compose *compose_new(PrefsAccount *account, const gchar *mailto,
842                      GPtrArray *attach_files)
843 {
844         return compose_generic_new(account, mailto, NULL, attach_files, NULL);
845 }
846
847 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
848 {
849         return compose_generic_new(account, NULL, item, NULL, NULL);
850 }
851
852 Compose *compose_new_with_list( PrefsAccount *account, GList *listAddress )
853 {
854         return compose_generic_new( account, NULL, NULL, NULL, listAddress );
855 }
856
857 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item,
858                              GPtrArray *attach_files, GList *listAddress )
859 {
860         Compose *compose;
861         GtkTextView *textview;
862         GtkTextBuffer *textbuf;
863         GtkTextIter iter;
864         GtkItemFactory *ifactory;
865
866         if (item && item->prefs && item->prefs->enable_default_account)
867                 account = account_find_from_id(item->prefs->default_account);
868
869         if (!account) account = cur_account;
870         g_return_val_if_fail(account != NULL, NULL);
871
872         compose = compose_create(account, COMPOSE_NEW);
873         ifactory = gtk_item_factory_from_widget(compose->menubar);
874
875         compose->replyinfo = NULL;
876         compose->fwdinfo   = NULL;
877
878         textview = GTK_TEXT_VIEW(compose->text);
879         textbuf = gtk_text_view_get_buffer(textview);
880         compose_create_tags(textview, compose);
881
882         undo_block(compose->undostruct);
883 #ifdef USE_ASPELL
884         if (item && item->prefs && item->prefs->enable_default_dictionary &&
885             compose->gtkaspell) 
886                 gtkaspell_change_dict(compose->gtkaspell, 
887                     item->prefs->default_dictionary);
888 #endif
889
890         if (account->auto_sig)
891                 compose_insert_sig(compose, FALSE);
892         gtk_text_buffer_get_start_iter(textbuf, &iter);
893         gtk_text_buffer_place_cursor(textbuf, &iter);
894
895         if (account->protocol != A_NNTP) {
896                 if (mailto && *mailto != '\0') {
897                         compose_entries_set(compose, mailto);
898
899                 } else if (item && item->prefs->enable_default_to) {
900                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
901                         compose_entry_mark_default_to(compose, item->prefs->default_to);
902                 }
903                 if (item && item->ret_rcpt) {
904                         menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
905                 }
906         } else {
907                 if (mailto) {
908                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
909                 } else if (item) {
910                         compose_entry_append(compose, item->path, COMPOSE_NEWSGROUPS);
911                 }
912                 /*
913                  * CLAWS: just don't allow return receipt request, even if the user
914                  * may want to send an email. simple but foolproof.
915                  */
916                 menu_set_sensitive(ifactory, "/Options/Request Return Receipt", FALSE); 
917         }
918         compose_add_field_list( compose, listAddress );
919
920         if (attach_files) {
921                 gint i;
922                 gchar *file;
923
924                 for (i = 0; i < attach_files->len; i++) {
925                         file = g_ptr_array_index(attach_files, i);
926                         compose_attach_append(compose, file, file, NULL);
927                 }
928         }
929
930         compose_show_first_last_header(compose, TRUE);
931
932         /* Set save folder */
933         if (item && item->prefs && item->prefs->save_copy_to_folder) {
934                 gchar *folderidentifier;
935
936                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
937                 folderidentifier = folder_item_get_identifier(item);
938                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
939                 g_free(folderidentifier);
940         }
941         
942         gtk_widget_grab_focus(compose->header_last->entry);
943
944         undo_unblock(compose->undostruct);
945
946         if (prefs_common.auto_exteditor)
947                 compose_exec_ext_editor(compose);
948
949         compose->modified = FALSE;
950         compose_set_title(compose);
951         return compose;
952 }
953
954 static void compose_force_encryption(Compose *compose, PrefsAccount *account,
955                 gboolean override_pref)
956 {
957         gchar *privacy = NULL;
958
959         g_return_if_fail(compose != NULL);
960         g_return_if_fail(account != NULL);
961
962         if (override_pref == FALSE && account->default_encrypt_reply == FALSE)
963                 return;
964
965         if (account->default_privacy_system
966         &&  strlen(account->default_privacy_system)) {
967                 privacy = account->default_privacy_system;
968         } else {
969                 GSList *privacy_avail = privacy_get_system_ids();
970                 if (privacy_avail && g_slist_length(privacy_avail)) {
971                         privacy = (gchar *)(privacy_avail->data);
972                 }
973         }
974         if (privacy != NULL) {
975                 compose->privacy_system = g_strdup(privacy);
976                 compose_update_privacy_system_menu_item(compose, FALSE);
977                 compose_use_encryption(compose, TRUE);
978         }
979 }       
980
981 static void compose_force_signing(Compose *compose, PrefsAccount *account)
982 {
983         gchar *privacy = NULL;
984
985         if (account->default_privacy_system
986         &&  strlen(account->default_privacy_system)) {
987                 privacy = account->default_privacy_system;
988         } else {
989                 GSList *privacy_avail = privacy_get_system_ids();
990                 if (privacy_avail && g_slist_length(privacy_avail)) {
991                         privacy = (gchar *)(privacy_avail->data);
992                 }
993         }
994         if (privacy != NULL) {
995                 compose->privacy_system = g_strdup(privacy);
996                 compose_update_privacy_system_menu_item(compose, FALSE);
997                 compose_use_signing(compose, TRUE);
998         }
999 }       
1000
1001 Compose *compose_reply_mode(ComposeMode mode, GSList *msginfo_list, gchar *body)
1002 {
1003         MsgInfo *msginfo;
1004         guint list_len;
1005         Compose *compose = NULL;
1006         g_return_val_if_fail(msginfo_list != NULL, NULL);
1007
1008         msginfo = (MsgInfo*)g_slist_nth_data(msginfo_list, 0);
1009         g_return_val_if_fail(msginfo != NULL, NULL);
1010
1011         list_len = g_slist_length(msginfo_list);
1012
1013         switch (mode) {
1014         case COMPOSE_REPLY:
1015                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1016                               FALSE, prefs_common.default_reply_list, FALSE, body);
1017                 break;
1018         case COMPOSE_REPLY_WITH_QUOTE:
1019                 compose = compose_reply(msginfo, TRUE, 
1020                         FALSE, prefs_common.default_reply_list, FALSE, body);
1021                 break;
1022         case COMPOSE_REPLY_WITHOUT_QUOTE:
1023                 compose = compose_reply(msginfo, FALSE, 
1024                         FALSE, prefs_common.default_reply_list, FALSE, NULL);
1025                 break;
1026         case COMPOSE_REPLY_TO_SENDER:
1027                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1028                               FALSE, FALSE, TRUE, body);
1029                 break;
1030         case COMPOSE_FOLLOWUP_AND_REPLY_TO:
1031                 compose = compose_followup_and_reply_to(msginfo,
1032                                               prefs_common.reply_with_quote,
1033                                               FALSE, FALSE, body);
1034                 break;
1035         case COMPOSE_REPLY_TO_SENDER_WITH_QUOTE:
1036                 compose = compose_reply(msginfo, TRUE, 
1037                         FALSE, FALSE, TRUE, body);
1038                 break;
1039         case COMPOSE_REPLY_TO_SENDER_WITHOUT_QUOTE:
1040                 compose = compose_reply(msginfo, FALSE, 
1041                         FALSE, FALSE, TRUE, NULL);
1042                 break;
1043         case COMPOSE_REPLY_TO_ALL:
1044                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1045                         TRUE, FALSE, FALSE, body);
1046                 break;
1047         case COMPOSE_REPLY_TO_ALL_WITH_QUOTE:
1048                 compose = compose_reply(msginfo, TRUE, 
1049                         TRUE, FALSE, FALSE, body);
1050                 break;
1051         case COMPOSE_REPLY_TO_ALL_WITHOUT_QUOTE:
1052                 compose = compose_reply(msginfo, FALSE, 
1053                         TRUE, FALSE, FALSE, NULL);
1054                 break;
1055         case COMPOSE_REPLY_TO_LIST:
1056                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1057                         FALSE, TRUE, FALSE, body);
1058                 break;
1059         case COMPOSE_REPLY_TO_LIST_WITH_QUOTE:
1060                 compose = compose_reply(msginfo, TRUE, 
1061                         FALSE, TRUE, FALSE, body);
1062                 break;
1063         case COMPOSE_REPLY_TO_LIST_WITHOUT_QUOTE:
1064                 compose = compose_reply(msginfo, FALSE, 
1065                         FALSE, TRUE, FALSE, NULL);
1066                 break;
1067         case COMPOSE_FORWARD:
1068                 if (prefs_common.forward_as_attachment) {
1069                         compose = compose_reply_mode(COMPOSE_FORWARD_AS_ATTACH, msginfo_list, body);
1070                         return compose;
1071                 } else {
1072                         compose = compose_reply_mode(COMPOSE_FORWARD_INLINE, msginfo_list, body);
1073                         return compose;
1074                 }
1075                 break;
1076         case COMPOSE_FORWARD_INLINE:
1077                 /* check if we reply to more than one Message */
1078                 if (list_len == 1) {
1079                         compose = compose_forward(NULL, msginfo, FALSE, body, FALSE);
1080                         break;
1081                 } 
1082                 /* more messages FALL THROUGH */
1083         case COMPOSE_FORWARD_AS_ATTACH:
1084                 compose = compose_forward_multiple(NULL, msginfo_list);
1085                 break;
1086         case COMPOSE_REDIRECT:
1087                 compose = compose_redirect(NULL, msginfo);
1088                 break;
1089         default:
1090                 g_warning("compose_reply(): invalid Compose Mode: %d\n", mode);
1091         }
1092         return compose;
1093 }
1094
1095 Compose *compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
1096                    gboolean to_ml, gboolean to_sender, 
1097                    const gchar *body)
1098 {
1099         return compose_generic_reply(msginfo, quote, to_all, to_ml, 
1100                               to_sender, FALSE, body);
1101 }
1102
1103 Compose *compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
1104                                    gboolean to_all,
1105                                    gboolean to_sender,
1106                                    const gchar *body)
1107 {
1108         return compose_generic_reply(msginfo, quote, to_all, FALSE, 
1109                               to_sender, TRUE, body);
1110 }
1111
1112 static void compose_extract_original_charset(Compose *compose)
1113 {
1114         MsgInfo *info = NULL;
1115         if (compose->replyinfo) {
1116                 info = compose->replyinfo;
1117         } else if (compose->fwdinfo) {
1118                 info = compose->fwdinfo;
1119         } else if (compose->targetinfo) {
1120                 info = compose->targetinfo;
1121         }
1122         if (info) {
1123                 MimeInfo *mimeinfo = procmime_scan_message(info);
1124                 MimeInfo *partinfo = mimeinfo;
1125                 while (partinfo && partinfo->type != MIMETYPE_TEXT)
1126                         partinfo = procmime_mimeinfo_next(partinfo);
1127                 if (partinfo) {
1128                         compose->orig_charset = 
1129                                 g_strdup(procmime_mimeinfo_get_parameter(
1130                                                 partinfo, "charset"));
1131                 }
1132                 procmime_mimeinfo_free_all(mimeinfo);
1133         }
1134 }
1135
1136 #define SIGNAL_BLOCK(buffer) {                                  \
1137         g_signal_handlers_block_by_func(G_OBJECT(buffer),       \
1138                                 G_CALLBACK(compose_changed_cb), \
1139                                 compose);                       \
1140         g_signal_handlers_block_by_func(G_OBJECT(buffer),       \
1141                                 G_CALLBACK(text_inserted),      \
1142                                 compose);                       \
1143 }
1144
1145 #define SIGNAL_UNBLOCK(buffer) {                                \
1146         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),     \
1147                                 G_CALLBACK(compose_changed_cb), \
1148                                 compose);                       \
1149         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),     \
1150                                 G_CALLBACK(text_inserted),      \
1151                                 compose);                       \
1152 }
1153
1154 static Compose *compose_generic_reply(MsgInfo *msginfo, gboolean quote,
1155                                   gboolean to_all, gboolean to_ml,
1156                                   gboolean to_sender,
1157                                   gboolean followup_and_reply_to,
1158                                   const gchar *body)
1159 {
1160         GtkItemFactory *ifactory;
1161         Compose *compose;
1162         PrefsAccount *account = NULL;
1163         PrefsAccount *reply_account;
1164         GtkTextView *textview;
1165         GtkTextBuffer *textbuf;
1166
1167         g_return_val_if_fail(msginfo != NULL, NULL);
1168         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1169
1170         account = account_get_reply_account(msginfo, prefs_common.reply_account_autosel);
1171         
1172         g_return_val_if_fail(account != NULL, NULL);
1173
1174         if (to_sender && account->protocol == A_NNTP &&
1175             !followup_and_reply_to) {
1176                 reply_account =
1177                         account_find_from_address(account->address);
1178                 if (!reply_account)
1179                         reply_account = compose_current_mail_account();
1180                 if (!reply_account)
1181                         return NULL;
1182         } else
1183                 reply_account = account;
1184
1185         compose = compose_create(account, COMPOSE_REPLY);
1186         ifactory = gtk_item_factory_from_widget(compose->menubar);
1187
1188         menu_set_active(ifactory, "/Options/Remove references", FALSE);
1189         menu_set_sensitive(ifactory, "/Options/Remove references", TRUE);
1190
1191         compose->replyinfo = procmsg_msginfo_get_full_info(msginfo);
1192
1193         if (!compose->replyinfo)
1194                 compose->replyinfo = procmsg_msginfo_copy(msginfo);
1195         
1196         compose_extract_original_charset(compose);
1197         
1198         if (msginfo->folder && msginfo->folder->ret_rcpt)
1199                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1200
1201         /* Set save folder */
1202         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1203                 gchar *folderidentifier;
1204
1205                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1206                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1207                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1208                 g_free(folderidentifier);
1209         }
1210
1211         if (compose_parse_header(compose, msginfo) < 0) return NULL;
1212         compose_reply_set_entry(compose, msginfo, to_all, to_ml, 
1213                                 to_sender, followup_and_reply_to);
1214         compose_show_first_last_header(compose, TRUE);
1215
1216         textview = (GTK_TEXT_VIEW(compose->text));
1217         textbuf = gtk_text_view_get_buffer(textview);
1218         compose_create_tags(textview, compose);
1219
1220         undo_block(compose->undostruct);
1221 #ifdef USE_ASPELL
1222         if (msginfo->folder && msginfo->folder->prefs && 
1223             msginfo->folder->prefs && 
1224             msginfo->folder->prefs->enable_default_dictionary &&
1225             compose->gtkaspell)
1226                 gtkaspell_change_dict(compose->gtkaspell, 
1227                     msginfo->folder->prefs->default_dictionary);
1228 #endif
1229
1230         if (quote) {
1231                 gchar *qmark;
1232
1233                 if (prefs_common.quotemark && *prefs_common.quotemark)
1234                         qmark = prefs_common.quotemark;
1235                 else
1236                         qmark = "> ";
1237
1238                 compose_quote_fmt(compose, compose->replyinfo,
1239                                   prefs_common.quotefmt,
1240                                   qmark, body, FALSE);
1241         }
1242         if (procmime_msginfo_is_encrypted(compose->replyinfo)) {
1243                 compose_force_encryption(compose, account, FALSE);
1244         }
1245
1246         SIGNAL_BLOCK(textbuf);
1247         
1248         if (account->auto_sig)
1249                 compose_insert_sig(compose, FALSE);
1250
1251         compose_wrap_all(compose);
1252
1253         SIGNAL_UNBLOCK(textbuf);
1254         
1255         gtk_widget_grab_focus(compose->text);
1256
1257         undo_unblock(compose->undostruct);
1258
1259         if (prefs_common.auto_exteditor)
1260                 compose_exec_ext_editor(compose);
1261                 
1262         compose->modified = FALSE;
1263         compose_set_title(compose);
1264         return compose;
1265 }
1266
1267 #define INSERT_FW_HEADER(var, hdr) \
1268 if (msginfo->var && *msginfo->var) { \
1269         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1270         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1271         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1272 }
1273
1274 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1275                          gboolean as_attach, const gchar *body,
1276                          gboolean no_extedit)
1277 {
1278         Compose *compose;
1279         GtkTextView *textview;
1280         GtkTextBuffer *textbuf;
1281         GtkTextIter iter;
1282
1283         g_return_val_if_fail(msginfo != NULL, NULL);
1284         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1285
1286         if (!account && 
1287             !(account = compose_guess_forward_account_from_msginfo
1288                                 (msginfo)))
1289                 account = cur_account;
1290
1291         compose = compose_create(account, COMPOSE_FORWARD);
1292
1293         compose->fwdinfo = procmsg_msginfo_get_full_info(msginfo);
1294         if (!compose->fwdinfo)
1295                 compose->fwdinfo = procmsg_msginfo_copy(msginfo);
1296
1297         compose_extract_original_charset(compose);
1298
1299         if (msginfo->subject && *msginfo->subject) {
1300                 gchar *buf, *buf2, *p;
1301
1302                 buf = p = g_strdup(msginfo->subject);
1303                 p += subject_get_prefix_length(p);
1304                 memmove(buf, p, strlen(p) + 1);
1305
1306                 buf2 = g_strdup_printf("Fw: %s", buf);
1307                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1308                 
1309                 g_free(buf);
1310                 g_free(buf2);
1311         }
1312
1313         textview = GTK_TEXT_VIEW(compose->text);
1314         textbuf = gtk_text_view_get_buffer(textview);
1315         compose_create_tags(textview, compose);
1316         
1317         undo_block(compose->undostruct);
1318         if (as_attach) {
1319                 gchar *msgfile;
1320
1321                 msgfile = procmsg_get_message_file_path(msginfo);
1322                 if (!is_file_exist(msgfile))
1323                         g_warning("%s: file not exist\n", msgfile);
1324                 else
1325                         compose_attach_append(compose, msgfile, msgfile,
1326                                               "message/rfc822");
1327
1328                 g_free(msgfile);
1329         } else {
1330                 gchar *qmark;
1331                 MsgInfo *full_msginfo;
1332
1333                 full_msginfo = procmsg_msginfo_get_full_info(msginfo);
1334                 if (!full_msginfo)
1335                         full_msginfo = procmsg_msginfo_copy(msginfo);
1336
1337                 if (prefs_common.fw_quotemark &&
1338                     *prefs_common.fw_quotemark)
1339                         qmark = prefs_common.fw_quotemark;
1340                 else
1341                         qmark = "> ";
1342
1343                 compose_quote_fmt(compose, full_msginfo,
1344                                   prefs_common.fw_quotefmt,
1345                                   qmark, body, FALSE);
1346                 compose_attach_parts(compose, msginfo);
1347
1348                 procmsg_msginfo_free(full_msginfo);
1349         }
1350
1351         SIGNAL_BLOCK(textbuf);
1352
1353         if (account->auto_sig)
1354                 compose_insert_sig(compose, FALSE);
1355
1356         compose_wrap_all(compose);
1357
1358         SIGNAL_UNBLOCK(textbuf);
1359         
1360         gtk_text_buffer_get_start_iter(textbuf, &iter);
1361         gtk_text_buffer_place_cursor(textbuf, &iter);
1362
1363         gtk_widget_grab_focus(compose->header_last->entry);
1364
1365         if (!no_extedit && prefs_common.auto_exteditor)
1366                 compose_exec_ext_editor(compose);
1367         
1368         /*save folder*/
1369         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1370                 gchar *folderidentifier;
1371
1372                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1373                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1374                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1375                 g_free(folderidentifier);
1376         }
1377
1378         undo_unblock(compose->undostruct);
1379         
1380         compose->modified = FALSE;
1381         compose_set_title(compose);
1382         return compose;
1383 }
1384
1385 #undef INSERT_FW_HEADER
1386
1387 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1388 {
1389         Compose *compose;
1390         GtkTextView *textview;
1391         GtkTextBuffer *textbuf;
1392         GtkTextIter iter;
1393         GSList *msginfo;
1394         gchar *msgfile;
1395         gboolean single_mail = TRUE;
1396         
1397         g_return_val_if_fail(msginfo_list != NULL, NULL);
1398
1399         if (g_slist_length(msginfo_list) > 1)
1400                 single_mail = FALSE;
1401
1402         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next)
1403                 if (((MsgInfo *)msginfo->data)->folder == NULL)
1404                         return NULL;
1405
1406         /* guess account from first selected message */
1407         if (!account && 
1408             !(account = compose_guess_forward_account_from_msginfo
1409                                 (msginfo_list->data)))
1410                 account = cur_account;
1411
1412         g_return_val_if_fail(account != NULL, NULL);
1413
1414         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1415                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1416                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1417         }
1418
1419         compose = compose_create(account, COMPOSE_FORWARD);
1420
1421         textview = GTK_TEXT_VIEW(compose->text);
1422         textbuf = gtk_text_view_get_buffer(textview);
1423         compose_create_tags(textview, compose);
1424         
1425         undo_block(compose->undostruct);
1426         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1427                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1428                 if (!is_file_exist(msgfile))
1429                         g_warning("%s: file not exist\n", msgfile);
1430                 else
1431                         compose_attach_append(compose, msgfile, msgfile,
1432                                 "message/rfc822");
1433                 g_free(msgfile);
1434         }
1435         
1436         if (single_mail) {
1437                 MsgInfo *info = (MsgInfo *)msginfo_list->data;
1438                 if (info->subject && *info->subject) {
1439                         gchar *buf, *buf2, *p;
1440
1441                         buf = p = g_strdup(info->subject);
1442                         p += subject_get_prefix_length(p);
1443                         memmove(buf, p, strlen(p) + 1);
1444
1445                         buf2 = g_strdup_printf("Fw: %s", buf);
1446                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1447
1448                         g_free(buf);
1449                         g_free(buf2);
1450                 }
1451         } else {
1452                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1453                         _("Fw: multiple emails"));
1454         }
1455
1456         SIGNAL_BLOCK(textbuf);
1457         
1458         if (account->auto_sig)
1459                 compose_insert_sig(compose, FALSE);
1460
1461         compose_wrap_all(compose);
1462
1463         SIGNAL_UNBLOCK(textbuf);
1464         
1465         gtk_text_buffer_get_start_iter(textbuf, &iter);
1466         gtk_text_buffer_place_cursor(textbuf, &iter);
1467
1468         gtk_widget_grab_focus(compose->header_last->entry);
1469         undo_unblock(compose->undostruct);
1470         compose->modified = FALSE;
1471         compose_set_title(compose);
1472         return compose;
1473 }
1474
1475 static gboolean compose_is_sig_separator(Compose *compose, GtkTextBuffer *textbuf, GtkTextIter *iter) 
1476 {
1477         GtkTextIter start = *iter;
1478         GtkTextIter end_iter;
1479         int start_pos = gtk_text_iter_get_offset(&start);
1480         gchar *str = NULL;
1481         if (!compose->account->sig_sep)
1482                 return FALSE;
1483         
1484         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1485                 start_pos+strlen(compose->account->sig_sep));
1486
1487         /* check sig separator */
1488         str = gtk_text_iter_get_text(&start, &end_iter);
1489         if (!strcmp(str, compose->account->sig_sep)) {
1490                 gchar *tmp = NULL;
1491                 /* check end of line (\n) */
1492                 gtk_text_buffer_get_iter_at_offset(textbuf, &start,
1493                         start_pos+strlen(compose->account->sig_sep));
1494                 gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1495                         start_pos+strlen(compose->account->sig_sep)+1);
1496                 tmp = gtk_text_iter_get_text(&start, &end_iter);
1497                 if (!strcmp(tmp,"\n")) {
1498                         g_free(str);
1499                         g_free(tmp);
1500                         return TRUE;
1501                 }
1502                 g_free(tmp);    
1503         }
1504         g_free(str);
1505
1506         return FALSE;
1507 }
1508
1509 static void compose_colorize_signature(Compose *compose)
1510 {
1511         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
1512         GtkTextIter iter;
1513         GtkTextIter end_iter;
1514         gtk_text_buffer_get_start_iter(buffer, &iter);
1515         while (gtk_text_iter_forward_line(&iter))
1516                 if (compose_is_sig_separator(compose, buffer, &iter)) {
1517                         gtk_text_buffer_get_end_iter(buffer, &end_iter);
1518                         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &end_iter);
1519                 }
1520 }
1521
1522 void compose_reedit(MsgInfo *msginfo)
1523 {
1524         Compose *compose = NULL;
1525         PrefsAccount *account = NULL;
1526         GtkTextView *textview;
1527         GtkTextBuffer *textbuf;
1528         GtkTextMark *mark;
1529         GtkTextIter iter;
1530         FILE *fp;
1531         gchar buf[BUFFSIZE];
1532         gboolean use_signing = FALSE;
1533         gboolean use_encryption = FALSE;
1534         gchar *privacy_system = NULL;
1535
1536         g_return_if_fail(msginfo != NULL);
1537         g_return_if_fail(msginfo->folder != NULL);
1538
1539         if (compose_put_existing_to_front(msginfo)) 
1540                 return;
1541
1542         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1543             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1544                 gchar queueheader_buf[BUFFSIZE];
1545                 gint id, param;
1546
1547                 /* Select Account from queue headers */
1548                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1549                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1550                         id = atoi(&queueheader_buf[strlen("X-Sylpheed-Account-Id:")]);
1551                         account = account_find_from_id(id);
1552                 }
1553                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1554                                              sizeof(queueheader_buf), "NAID:")) {
1555                         id = atoi(&queueheader_buf[strlen("NAID:")]);
1556                         account = account_find_from_id(id);
1557                 }
1558                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1559                                                     sizeof(queueheader_buf), "MAID:")) {
1560                         id = atoi(&queueheader_buf[strlen("MAID:")]);
1561                         account = account_find_from_id(id);
1562                 }
1563                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1564                                                                 sizeof(queueheader_buf), "S:")) {
1565                         account = account_find_from_address(queueheader_buf);
1566                 }
1567                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1568                                              sizeof(queueheader_buf), "X-Sylpheed-Sign:")) {
1569                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Sign:")]);
1570                         use_signing = param;
1571                         
1572                 }
1573                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1574                                              sizeof(queueheader_buf), "X-Sylpheed-Encrypt:")) {
1575                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Encrypt:")]);
1576                         use_encryption = param;
1577                 }
1578                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1579                                             sizeof(queueheader_buf), "X-Sylpheed-Privacy-System:")) {
1580                         privacy_system = g_strdup(&queueheader_buf[strlen("X-Sylpheed-Privacy-System:")]);
1581                 }
1582                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1583                                              sizeof(queueheader_buf), "X-Priority: ")) {
1584                         param = atoi(&queueheader_buf[strlen("X-Priority: ")]); /* mind the space */
1585                         compose->priority = param;
1586                 }
1587         } else 
1588                 account = msginfo->folder->folder->account;
1589
1590         if (!account && prefs_common.reedit_account_autosel) {
1591                 gchar from[BUFFSIZE];
1592                 if (!procheader_get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1593                         extract_address(from);
1594                         account = account_find_from_address(from);
1595                 }
1596         }
1597         if (!account) account = cur_account;
1598         g_return_if_fail(account != NULL);
1599
1600         compose = compose_create(account, COMPOSE_REEDIT);
1601         if (privacy_system != NULL) {
1602                 compose->privacy_system = privacy_system;
1603                 compose_use_signing(compose, use_signing);
1604                 compose_use_encryption(compose, use_encryption);
1605                 compose_update_privacy_system_menu_item(compose, FALSE);
1606         } else {
1607                 activate_privacy_system(compose, account, FALSE);
1608         }
1609         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1610
1611         compose_extract_original_charset(compose);
1612
1613         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1614             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1615                 gchar queueheader_buf[BUFFSIZE];
1616
1617                 /* Set message save folder */
1618                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1619                         gint startpos = 0;
1620
1621                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1622                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1623                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1624                 }
1625                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "RRCPT:")) {
1626                         gint active = atoi(&queueheader_buf[strlen("RRCPT:")]);
1627                         if (active) {
1628                                 GtkItemFactory *ifactory;
1629                                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1630                                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1631                         }
1632                 }
1633         }
1634         
1635         if (compose_parse_header(compose, msginfo) < 0) return;
1636         compose_reedit_set_entry(compose, msginfo);
1637
1638         textview = GTK_TEXT_VIEW(compose->text);
1639         textbuf = gtk_text_view_get_buffer(textview);
1640         compose_create_tags(textview, compose);
1641
1642         mark = gtk_text_buffer_get_insert(textbuf);
1643         gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1644
1645         g_signal_handlers_block_by_func(G_OBJECT(textbuf),
1646                                         G_CALLBACK(compose_changed_cb),
1647                                         compose);
1648         
1649         if (procmime_msginfo_is_encrypted(msginfo)) {
1650                 fp = procmime_get_first_encrypted_text_content(msginfo);
1651                 if (fp) 
1652                         compose_force_encryption(compose, account, TRUE);
1653         } else
1654                 fp = procmime_get_first_text_content(msginfo);
1655         if (fp == NULL)
1656                 g_warning("Can't get text part\n");
1657
1658         if (fp != NULL) {
1659                 gboolean prev_autowrap = compose->autowrap;
1660
1661                 compose->autowrap = FALSE;
1662                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1663                         strcrchomp(buf);
1664                         gtk_text_buffer_insert(textbuf, &iter, buf, -1);
1665                 }
1666                 compose_wrap_all_full(compose, FALSE);
1667                 compose->autowrap = prev_autowrap;
1668                 fclose(fp);
1669         }
1670         
1671         compose_attach_parts(compose, msginfo);
1672
1673         compose_colorize_signature(compose);
1674
1675         g_signal_handlers_unblock_by_func(G_OBJECT(textbuf),
1676                                         G_CALLBACK(compose_changed_cb),
1677                                         compose);
1678
1679         gtk_widget_grab_focus(compose->text);
1680
1681         if (prefs_common.auto_exteditor)
1682                 compose_exec_ext_editor(compose);
1683         compose->modified = FALSE;
1684         compose_set_title(compose);
1685 }
1686
1687 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
1688 {
1689         Compose *compose;
1690         gchar *filename;
1691         GtkItemFactory *ifactory;
1692         FolderItem *item;
1693
1694         g_return_val_if_fail(msginfo != NULL, NULL);
1695
1696         if (!account)
1697                 account = account_get_reply_account(msginfo,
1698                                         prefs_common.reply_account_autosel);
1699         g_return_val_if_fail(account != NULL, NULL);
1700
1701         compose = compose_create(account, COMPOSE_REDIRECT);
1702         ifactory = gtk_item_factory_from_widget(compose->menubar);
1703         compose_create_tags(GTK_TEXT_VIEW(compose->text), compose);
1704         compose->replyinfo = NULL;
1705         compose->fwdinfo = NULL;
1706
1707         compose_show_first_last_header(compose, TRUE);
1708
1709         gtk_widget_grab_focus(compose->header_last->entry);
1710
1711         filename = procmsg_get_message_file_path(msginfo);
1712         if (filename == NULL)
1713                 return NULL;
1714
1715         compose->redirect_filename = filename;
1716         
1717         /* Set save folder */
1718         item = msginfo->folder;
1719         if (item && item->prefs && item->prefs->save_copy_to_folder) {
1720                 gchar *folderidentifier;
1721
1722                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
1723                 folderidentifier = folder_item_get_identifier(item);
1724                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1725                 g_free(folderidentifier);
1726         }
1727
1728         compose_attach_parts(compose, msginfo);
1729
1730         if (msginfo->subject)
1731                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1732                                    msginfo->subject);
1733         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1734
1735         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL, FALSE);
1736         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), FALSE);
1737
1738         compose_colorize_signature(compose);
1739
1740         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1741         menu_set_sensitive(ifactory, "/Add...", FALSE);
1742         menu_set_sensitive(ifactory, "/Remove", FALSE);
1743         menu_set_sensitive(ifactory, "/Properties...", FALSE);
1744
1745         ifactory = gtk_item_factory_from_widget(compose->menubar);
1746         menu_set_sensitive(ifactory, "/Message/Save", FALSE);
1747         menu_set_sensitive(ifactory, "/Message/Insert file", FALSE);
1748         menu_set_sensitive(ifactory, "/Message/Attach file", FALSE);
1749         menu_set_sensitive(ifactory, "/Message/Insert signature", FALSE);
1750         menu_set_sensitive(ifactory, "/Edit", FALSE);
1751         menu_set_sensitive(ifactory, "/Options", FALSE);
1752         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1753         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1754         
1755         if (compose->toolbar->draft_btn)
1756                 gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1757         if (compose->toolbar->insert_btn)
1758                 gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1759         if (compose->toolbar->attach_btn)
1760                 gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1761         if (compose->toolbar->sig_btn)
1762                 gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1763         if (compose->toolbar->exteditor_btn)
1764                 gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1765         if (compose->toolbar->linewrap_current_btn)
1766                 gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, FALSE);
1767         if (compose->toolbar->linewrap_all_btn)
1768                 gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, FALSE);
1769
1770         compose->modified = FALSE;
1771         compose_set_title(compose);
1772         return compose;
1773 }
1774
1775 GList *compose_get_compose_list(void)
1776 {
1777         return compose_list;
1778 }
1779
1780 void compose_entry_append(Compose *compose, const gchar *address,
1781                           ComposeEntryType type)
1782 {
1783         gchar *header;
1784         gchar *cur, *begin;
1785         gboolean in_quote = FALSE;
1786         if (!address || *address == '\0') return;
1787
1788         switch (type) {
1789         case COMPOSE_CC:
1790                 header = N_("Cc:");
1791                 break;
1792         case COMPOSE_BCC:
1793                 header = N_("Bcc:");
1794                 break;
1795         case COMPOSE_REPLYTO:
1796                 header = N_("Reply-To:");
1797                 break;
1798         case COMPOSE_NEWSGROUPS:
1799                 header = N_("Newsgroups:");
1800                 break;
1801         case COMPOSE_FOLLOWUPTO:
1802                 header = N_( "Followup-To:");
1803                 break;
1804         case COMPOSE_TO:
1805         default:
1806                 header = N_("To:");
1807                 break;
1808         }
1809         header = prefs_common.trans_hdr ? gettext(header) : header;
1810         
1811         cur = begin = (gchar *)address;
1812         
1813         /* we separate the line by commas, but not if we're inside a quoted
1814          * string */
1815         while (*cur != '\0') {
1816                 if (*cur == '"') 
1817                         in_quote = !in_quote;
1818                 if (*cur == ',' && !in_quote) {
1819                         gchar *tmp = g_strdup(begin);
1820                         gchar *o_tmp = tmp;
1821                         tmp[cur-begin]='\0';
1822                         cur++;
1823                         begin = cur;
1824                         while (*tmp == ' ')
1825                                 tmp++;
1826                         compose_add_header_entry(compose, header, tmp);
1827                         g_free(o_tmp);
1828                         continue;
1829                 }
1830                 cur++;
1831         }
1832         if (begin < cur) {
1833                 gchar *tmp = g_strdup(begin);
1834                 gchar *o_tmp = tmp;
1835                 tmp[cur-begin]='\0';
1836                 cur++;
1837                 begin = cur;
1838                 while (*tmp == ' ')
1839                         tmp++;
1840                 compose_add_header_entry(compose, header, tmp);
1841                 g_free(o_tmp);          
1842         }
1843 }
1844
1845 void compose_entry_mark_default_to(Compose *compose, const gchar *mailto)
1846 {
1847         static GdkColor yellow;
1848         static GdkColor black;
1849         static gboolean yellow_initialised = FALSE;
1850         GSList *h_list;
1851         GtkEntry *entry;
1852                 
1853         if (!yellow_initialised) {
1854                 gdk_color_parse("#f5f6be", &yellow);
1855                 gdk_color_parse("#000000", &black);
1856                 yellow_initialised = gdk_colormap_alloc_color(
1857                         gdk_colormap_get_system(), &yellow, FALSE, TRUE);
1858                 yellow_initialised &= gdk_colormap_alloc_color(
1859                         gdk_colormap_get_system(), &black, FALSE, TRUE);
1860         }
1861
1862         for (h_list = compose->header_list; h_list != NULL; h_list = h_list->next) {
1863                 entry = GTK_ENTRY(((ComposeHeaderEntry *)h_list->data)->entry);
1864                 if (gtk_entry_get_text(entry) && 
1865                     !g_utf8_collate(gtk_entry_get_text(entry), mailto)) {
1866                         if (yellow_initialised) {
1867                                 gtk_widget_modify_base(
1868                                         GTK_WIDGET(((ComposeHeaderEntry *)h_list->data)->entry),
1869                                         GTK_STATE_NORMAL, &yellow);
1870                                 gtk_widget_modify_text(
1871                                         GTK_WIDGET(((ComposeHeaderEntry *)h_list->data)->entry),
1872                                         GTK_STATE_NORMAL, &black);
1873                         }
1874                 }
1875         }
1876 }
1877
1878 void compose_toolbar_cb(gint action, gpointer data)
1879 {
1880         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1881         Compose *compose = (Compose*)toolbar_item->parent;
1882         
1883         g_return_if_fail(compose != NULL);
1884
1885         switch(action) {
1886         case A_SEND:
1887                 compose_send_cb(compose, 0, NULL);
1888                 break;
1889         case A_SENDL:
1890                 compose_send_later_cb(compose, 0, NULL);
1891                 break;
1892         case A_DRAFT:
1893                 compose_draft_cb(compose, COMPOSE_QUIT_EDITING, NULL);
1894                 break;
1895         case A_INSERT:
1896                 compose_insert_file_cb(compose, 0, NULL);
1897                 break;
1898         case A_ATTACH:
1899                 compose_attach_cb(compose, 0, NULL);
1900                 break;
1901         case A_SIG:
1902                 compose_insert_sig(compose, FALSE);
1903                 break;
1904         case A_EXTEDITOR:
1905                 compose_ext_editor_cb(compose, 0, NULL);
1906                 break;
1907         case A_LINEWRAP_CURRENT:
1908                 compose_beautify_paragraph(compose, NULL, TRUE);
1909                 break;
1910         case A_LINEWRAP_ALL:
1911                 compose_wrap_all_full(compose, TRUE);
1912                 break;
1913         case A_ADDRBOOK:
1914                 compose_address_cb(compose, 0, NULL);
1915                 break;
1916 #ifdef USE_ASPELL
1917         case A_CHECK_SPELLING:
1918                 compose_check_all(compose);
1919                 break;
1920 #endif
1921         default:
1922                 break;
1923         }
1924 }
1925
1926 static void compose_entries_set(Compose *compose, const gchar *mailto)
1927 {
1928         gchar *to = NULL;
1929         gchar *cc = NULL;
1930         gchar *subject = NULL;
1931         gchar *body = NULL;
1932         gchar *temp = NULL;
1933         gint  len = 0;
1934
1935         scan_mailto_url(mailto, &to, &cc, NULL, &subject, &body);
1936
1937         if (to)
1938                 compose_entry_append(compose, to, COMPOSE_TO);
1939         if (cc)
1940                 compose_entry_append(compose, cc, COMPOSE_CC);
1941         if (subject) {
1942                 if (!g_utf8_validate (subject, -1, NULL)) {
1943                         temp = g_locale_to_utf8 (subject, -1, NULL, &len, NULL);
1944                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), temp);
1945                         g_free(temp);
1946                 } else {
1947                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1948                 }
1949         }
1950         if (body) {
1951                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1952                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1953                 GtkTextMark *mark;
1954                 GtkTextIter iter;
1955                 gboolean prev_autowrap = compose->autowrap;
1956
1957                 compose->autowrap = FALSE;
1958
1959                 mark = gtk_text_buffer_get_insert(buffer);
1960                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1961
1962                 if (!g_utf8_validate (body, -1, NULL)) {
1963                         temp = g_locale_to_utf8 (body, -1, NULL, &len, NULL);
1964                         gtk_text_buffer_insert(buffer, &iter, temp, -1);
1965                         g_free(temp);
1966                 } else {
1967                         gtk_text_buffer_insert(buffer, &iter, body, -1);
1968                 }
1969                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
1970
1971                 compose->autowrap = prev_autowrap;
1972                 if (compose->autowrap)
1973                         compose_wrap_all(compose);
1974         }
1975
1976         g_free(to);
1977         g_free(cc);
1978         g_free(subject);
1979         g_free(body);
1980 }
1981
1982 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1983 {
1984         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1985                                        {"Cc:",          NULL, TRUE},
1986                                        {"References:",  NULL, FALSE},
1987                                        {"Bcc:",         NULL, TRUE},
1988                                        {"Newsgroups:",  NULL, TRUE},
1989                                        {"Followup-To:", NULL, TRUE},
1990                                        {"List-Post:",   NULL, FALSE},
1991                                        {"X-Priority:",  NULL, FALSE},
1992                                        {NULL,           NULL, FALSE}};
1993
1994         enum
1995         {
1996                 H_REPLY_TO      = 0,
1997                 H_CC            = 1,
1998                 H_REFERENCES    = 2,
1999                 H_BCC           = 3,
2000                 H_NEWSGROUPS    = 4,
2001                 H_FOLLOWUP_TO   = 5,
2002                 H_LIST_POST     = 6,
2003                 H_X_PRIORITY    = 7
2004         };
2005
2006         FILE *fp;
2007
2008         g_return_val_if_fail(msginfo != NULL, -1);
2009
2010         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
2011         procheader_get_header_fields(fp, hentry);
2012         fclose(fp);
2013
2014         if (hentry[H_REPLY_TO].body != NULL) {
2015                 if (hentry[H_REPLY_TO].body[0] != '\0') {
2016                         compose->replyto =
2017                                 conv_unmime_header(hentry[H_REPLY_TO].body,
2018                                                    NULL);
2019                 }
2020                 g_free(hentry[H_REPLY_TO].body);
2021                 hentry[H_REPLY_TO].body = NULL;
2022         }
2023         if (hentry[H_CC].body != NULL) {
2024                 compose->cc = conv_unmime_header(hentry[H_CC].body, NULL);
2025                 g_free(hentry[H_CC].body);
2026                 hentry[H_CC].body = NULL;
2027         }
2028         if (hentry[H_REFERENCES].body != NULL) {
2029                 if (compose->mode == COMPOSE_REEDIT)
2030                         compose->references = hentry[H_REFERENCES].body;
2031                 else {
2032                         compose->references = compose_parse_references
2033                                 (hentry[H_REFERENCES].body, msginfo->msgid);
2034                         g_free(hentry[H_REFERENCES].body);
2035                 }
2036                 hentry[H_REFERENCES].body = NULL;
2037         }
2038         if (hentry[H_BCC].body != NULL) {
2039                 if (compose->mode == COMPOSE_REEDIT)
2040                         compose->bcc =
2041                                 conv_unmime_header(hentry[H_BCC].body, NULL);
2042                 g_free(hentry[H_BCC].body);
2043                 hentry[H_BCC].body = NULL;
2044         }
2045         if (hentry[H_NEWSGROUPS].body != NULL) {
2046                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
2047                 hentry[H_NEWSGROUPS].body = NULL;
2048         }
2049         if (hentry[H_FOLLOWUP_TO].body != NULL) {
2050                 if (hentry[H_FOLLOWUP_TO].body[0] != '\0') {
2051                         compose->followup_to =
2052                                 conv_unmime_header(hentry[H_FOLLOWUP_TO].body,
2053                                                    NULL);
2054                 }
2055                 g_free(hentry[H_FOLLOWUP_TO].body);
2056                 hentry[H_FOLLOWUP_TO].body = NULL;
2057         }
2058         if (hentry[H_LIST_POST].body != NULL) {
2059                 gchar *to = NULL;
2060
2061                 extract_address(hentry[H_LIST_POST].body);
2062                 if (hentry[H_LIST_POST].body[0] != '\0') {
2063                         scan_mailto_url(hentry[H_LIST_POST].body,
2064                                         &to, NULL, NULL, NULL, NULL);
2065                         if (to) {
2066                                 g_free(compose->ml_post);
2067                                 compose->ml_post = to;
2068                         }
2069                 }
2070                 g_free(hentry[H_LIST_POST].body);
2071                 hentry[H_LIST_POST].body = NULL;
2072         }
2073
2074         /* CLAWS - X-Priority */
2075         if (compose->mode == COMPOSE_REEDIT)
2076                 if (hentry[H_X_PRIORITY].body != NULL) {
2077                         gint priority;
2078                         
2079                         priority = atoi(hentry[H_X_PRIORITY].body);
2080                         g_free(hentry[H_X_PRIORITY].body);
2081                         
2082                         hentry[H_X_PRIORITY].body = NULL;
2083                         
2084                         if (priority < PRIORITY_HIGHEST || 
2085                             priority > PRIORITY_LOWEST)
2086                                 priority = PRIORITY_NORMAL;
2087                         
2088                         compose->priority =  priority;
2089                 }
2090  
2091         if (compose->mode == COMPOSE_REEDIT) {
2092                 if (msginfo->inreplyto && *msginfo->inreplyto)
2093                         compose->inreplyto = g_strdup(msginfo->inreplyto);
2094                 return 0;
2095         }
2096
2097         if (msginfo->msgid && *msginfo->msgid)
2098                 compose->inreplyto = g_strdup(msginfo->msgid);
2099
2100         if (!compose->references) {
2101                 if (msginfo->msgid && *msginfo->msgid) {
2102                         if (msginfo->inreplyto && *msginfo->inreplyto)
2103                                 compose->references =
2104                                         g_strdup_printf("<%s>\n\t<%s>",
2105                                                         msginfo->inreplyto,
2106                                                         msginfo->msgid);
2107                         else
2108                                 compose->references =
2109                                         g_strconcat("<", msginfo->msgid, ">",
2110                                                     NULL);
2111                 } else if (msginfo->inreplyto && *msginfo->inreplyto) {
2112                         compose->references =
2113                                 g_strconcat("<", msginfo->inreplyto, ">",
2114                                             NULL);
2115                 }
2116         }
2117
2118         return 0;
2119 }
2120
2121 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
2122 {
2123         GSList *ref_id_list, *cur;
2124         GString *new_ref;
2125         gchar *new_ref_str;
2126
2127         ref_id_list = references_list_append(NULL, ref);
2128         if (!ref_id_list) return NULL;
2129         if (msgid && *msgid)
2130                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
2131
2132         for (;;) {
2133                 gint len = 0;
2134
2135                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
2136                         /* "<" + Message-ID + ">" + CR+LF+TAB */
2137                         len += strlen((gchar *)cur->data) + 5;
2138
2139                 if (len > MAX_REFERENCES_LEN) {
2140                         /* remove second message-ID */
2141                         if (ref_id_list && ref_id_list->next &&
2142                             ref_id_list->next->next) {
2143                                 g_free(ref_id_list->next->data);
2144                                 ref_id_list = g_slist_remove
2145                                         (ref_id_list, ref_id_list->next->data);
2146                         } else {
2147                                 slist_free_strings(ref_id_list);
2148                                 g_slist_free(ref_id_list);
2149                                 return NULL;
2150                         }
2151                 } else
2152                         break;
2153         }
2154
2155         new_ref = g_string_new("");
2156         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
2157                 if (new_ref->len > 0)
2158                         g_string_append(new_ref, "\n\t");
2159                 g_string_append_printf(new_ref, "<%s>", (gchar *)cur->data);
2160         }
2161
2162         slist_free_strings(ref_id_list);
2163         g_slist_free(ref_id_list);
2164
2165         new_ref_str = new_ref->str;
2166         g_string_free(new_ref, FALSE);
2167
2168         return new_ref_str;
2169 }
2170
2171 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
2172                                 const gchar *fmt, const gchar *qmark,
2173                                 const gchar *body, gboolean rewrap)
2174 {
2175         static MsgInfo dummyinfo;
2176         gchar *quote_str = NULL;
2177         gchar *buf;
2178         gboolean prev_autowrap;
2179         const gchar *trimmed_body = body;
2180         gint cursor_pos = -1;
2181         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2182         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2183         GtkTextIter iter;
2184         GtkTextMark *mark;
2185         
2186
2187         SIGNAL_BLOCK(buffer);
2188
2189         if (!msginfo)
2190                 msginfo = &dummyinfo;
2191
2192         if (qmark != NULL) {
2193                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
2194                 quote_fmt_scan_string(qmark);
2195                 quote_fmt_parse();
2196
2197                 buf = quote_fmt_get_buffer();
2198                 if (buf == NULL)
2199                         alertpanel_error(_("Quote mark format error."));
2200                 else
2201                         Xstrdup_a(quote_str, buf, goto error)
2202         }
2203
2204         if (fmt && *fmt != '\0') {
2205                 while (trimmed_body && strlen(trimmed_body) > 1
2206                         && trimmed_body[0]=='\n')
2207                         *trimmed_body++;
2208
2209                 quote_fmt_init(msginfo, quote_str, trimmed_body, FALSE);
2210                 quote_fmt_scan_string(fmt);
2211                 quote_fmt_parse();
2212
2213                 buf = quote_fmt_get_buffer();
2214                 if (buf == NULL) {
2215                         alertpanel_error(_("Message reply/forward format error."));
2216                         goto error;
2217                 }
2218         } else
2219                 buf = "";
2220
2221         prev_autowrap = compose->autowrap;
2222         compose->autowrap = FALSE;
2223
2224         mark = gtk_text_buffer_get_insert(buffer);
2225         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2226         if (g_utf8_validate(buf, -1, NULL)) { 
2227                 gtk_text_buffer_insert(buffer, &iter, buf, -1);
2228         } else {
2229                 gchar *tmpout = NULL;
2230                 tmpout = conv_codeset_strdup
2231                         (buf, conv_get_locale_charset_str(),
2232                          CS_INTERNAL);
2233                 if (!tmpout || !g_utf8_validate(tmpout, -1, NULL)) {
2234                         g_free(tmpout);
2235                         tmpout = g_malloc(strlen(buf)*2+1);
2236                         conv_localetodisp(tmpout, strlen(buf)*2+1, buf);
2237                 }
2238                 gtk_text_buffer_insert(buffer, &iter, tmpout, -1);
2239                 g_free(tmpout);
2240         }
2241
2242         cursor_pos = quote_fmt_get_cursor_pos();
2243         compose->set_cursor_pos = cursor_pos;
2244         if (cursor_pos == -1) {
2245                 cursor_pos = 0;
2246         }
2247         gtk_text_buffer_get_start_iter(buffer, &iter);
2248         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cursor_pos);
2249         gtk_text_buffer_place_cursor(buffer, &iter);
2250
2251         compose->autowrap = prev_autowrap;
2252         if (compose->autowrap && rewrap)
2253                 compose_wrap_all(compose);
2254
2255         goto ok;
2256
2257 error:
2258         buf = NULL;
2259 ok:
2260         SIGNAL_UNBLOCK(buffer);
2261
2262
2263         return buf;
2264 }
2265
2266 /* if ml_post is of type addr@host and from is of type
2267  * addr-anything@host, return TRUE
2268  */
2269 static gboolean is_subscription(const gchar *ml_post, const gchar *from)
2270 {
2271         gchar *left_ml = NULL;
2272         gchar *right_ml = NULL;
2273         gchar *left_from = NULL;
2274         gchar *right_from = NULL;
2275         gboolean result = FALSE;
2276         
2277         if (!ml_post || !from)
2278                 return FALSE;
2279         
2280         left_ml = g_strdup(ml_post);
2281         if (strstr(left_ml, "@")) {
2282                 right_ml = strstr(left_ml, "@")+1;
2283                 *(strstr(left_ml, "@")) = '\0';
2284         }
2285         
2286         left_from = g_strdup(from);
2287         if (strstr(left_from, "@")) {
2288                 right_from = strstr(left_from, "@")+1;
2289                 *(strstr(left_from, "@")) = '\0';
2290         }
2291         
2292         if (left_ml && left_from && right_ml && right_from
2293         &&  !strncmp(left_from, left_ml, strlen(left_ml))
2294         &&  !strcmp(right_from, right_ml)) {
2295                 result = TRUE;
2296         }
2297         g_free(left_ml);
2298         g_free(left_from);
2299         
2300         return result;
2301 }
2302
2303 static gboolean same_address(const gchar *addr1, const gchar *addr2)
2304 {
2305         gchar *my_addr1, *my_addr2;
2306         
2307         if (!addr1 || !addr2)
2308                 return FALSE;
2309
2310         Xstrdup_a(my_addr1, addr1, return FALSE);
2311         Xstrdup_a(my_addr2, addr2, return FALSE);
2312         
2313         extract_address(my_addr1);
2314         extract_address(my_addr2);
2315         
2316         return !strcmp(my_addr1, my_addr2);
2317 }
2318
2319 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
2320                                     gboolean to_all, gboolean to_ml,
2321                                     gboolean to_sender,
2322                                     gboolean followup_and_reply_to)
2323 {
2324         GSList *cc_list = NULL;
2325         GSList *cur;
2326         gchar *from = NULL;
2327         gchar *replyto = NULL;
2328         GHashTable *to_table;
2329
2330         gboolean reply_to_ml = FALSE;
2331         gboolean default_reply_to = FALSE;
2332
2333         g_return_if_fail(compose->account != NULL);
2334         g_return_if_fail(msginfo != NULL);
2335
2336         reply_to_ml = to_ml && compose->ml_post;
2337
2338         default_reply_to = msginfo->folder && 
2339                 msginfo->folder->prefs->enable_default_reply_to;
2340
2341         if (compose->account->protocol != A_NNTP) {
2342                 if (reply_to_ml && !default_reply_to) {
2343                         
2344                         gboolean is_subscr = is_subscription(compose->ml_post,
2345                                                              msginfo->from);
2346                         if (!is_subscr) {
2347                                 /* normal answer to ml post with a reply-to */
2348                                 compose_entry_append(compose,
2349                                            compose->ml_post,
2350                                            COMPOSE_TO);
2351                                 if (compose->replyto
2352                                 &&  !same_address(compose->ml_post, compose->replyto))
2353                                         compose_entry_append(compose,
2354                                                 compose->replyto,
2355                                                 COMPOSE_CC);
2356                         } else {
2357                                 /* answer to subscription confirmation */
2358                                 if (compose->replyto)
2359                                         compose_entry_append(compose,
2360                                                 compose->replyto,
2361                                                 COMPOSE_TO);
2362                                 else if (msginfo->from)
2363                                         compose_entry_append(compose,
2364                                                 msginfo->from,
2365                                                 COMPOSE_TO);
2366                         }
2367                 }
2368                 else if (!(to_all || to_sender) && default_reply_to) {
2369                         compose_entry_append(compose,
2370                             msginfo->folder->prefs->default_reply_to,
2371                             COMPOSE_TO);
2372                         compose_entry_mark_default_to(compose,
2373                                 msginfo->folder->prefs->default_reply_to);
2374                 } else {
2375                         gchar *tmp1 = NULL;
2376                         Xstrdup_a(tmp1, msginfo->from, return);
2377                         extract_address(tmp1);
2378                         if (to_all || to_sender ||
2379                             !account_find_from_address(tmp1))
2380                                 compose_entry_append(compose,
2381                                  (compose->replyto && !to_sender)
2382                                           ? compose->replyto :
2383                                           msginfo->from ? msginfo->from : "",
2384                                           COMPOSE_TO);
2385                         else if (!to_all && !to_sender) {
2386                                 /* reply to the last list of recipients */
2387                                 compose_entry_append(compose,
2388                                           msginfo->to ? msginfo->to : "",
2389                                           COMPOSE_TO);
2390                                 compose_entry_append(compose,
2391                                           msginfo->cc ? msginfo->cc : "",
2392                                           COMPOSE_CC);
2393                         }
2394                 }
2395         } else {
2396                 if (to_sender || (compose->followup_to && 
2397                         !strncmp(compose->followup_to, "poster", 6)))
2398                         compose_entry_append
2399                                 (compose, 
2400                                  (compose->replyto ? compose->replyto :
2401                                         msginfo->from ? msginfo->from : ""),
2402                                  COMPOSE_TO);
2403                                  
2404                 else if (followup_and_reply_to || to_all) {
2405                         compose_entry_append
2406                                 (compose,
2407                                  (compose->replyto ? compose->replyto :
2408                                  msginfo->from ? msginfo->from : ""),
2409                                  COMPOSE_TO);                           
2410                 
2411                         compose_entry_append
2412                                 (compose,
2413                                  compose->followup_to ? compose->followup_to :
2414                                  compose->newsgroups ? compose->newsgroups : "",
2415                                  COMPOSE_NEWSGROUPS);
2416                 } 
2417                 else 
2418                         compose_entry_append
2419                                 (compose,
2420                                  compose->followup_to ? compose->followup_to :
2421                                  compose->newsgroups ? compose->newsgroups : "",
2422                                  COMPOSE_NEWSGROUPS);
2423         }
2424
2425         if (msginfo->subject && *msginfo->subject) {
2426                 gchar *buf, *buf2;
2427                 guchar *p;
2428
2429                 buf = p = g_strdup(msginfo->subject);
2430                 p += subject_get_prefix_length(p);
2431                 memmove(buf, p, strlen(p) + 1);
2432
2433                 buf2 = g_strdup_printf("Re: %s", buf);
2434                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
2435
2436                 g_free(buf2);
2437                 g_free(buf);
2438         } else
2439                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
2440
2441         if (to_ml && compose->ml_post) return;
2442         if (!to_all || compose->account->protocol == A_NNTP) return;
2443
2444         if (compose->replyto) {
2445                 Xstrdup_a(replyto, compose->replyto, return);
2446                 extract_address(replyto);
2447         }
2448         if (msginfo->from) {
2449                 Xstrdup_a(from, msginfo->from, return);
2450                 extract_address(from);
2451         }
2452
2453         if (replyto && from)
2454                 cc_list = address_list_append_with_comments(cc_list, from);
2455         if (to_all && msginfo->folder && 
2456             msginfo->folder->prefs->enable_default_reply_to)
2457                 cc_list = address_list_append_with_comments(cc_list,
2458                                 msginfo->folder->prefs->default_reply_to);
2459         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
2460         cc_list = address_list_append_with_comments(cc_list, compose->cc);
2461
2462         to_table = g_hash_table_new(g_str_hash, g_str_equal);
2463         if (replyto)
2464                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
2465         if (compose->account)
2466                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
2467                                     GINT_TO_POINTER(1));
2468
2469         /* remove address on To: and that of current account */
2470         for (cur = cc_list; cur != NULL; ) {
2471                 GSList *next = cur->next;
2472                 gchar *addr;
2473
2474                 addr = g_strdup(cur->data);
2475                 extract_address(addr);
2476
2477                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
2478                         cc_list = g_slist_remove(cc_list, cur->data);
2479                 else
2480                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
2481
2482                 cur = next;
2483         }
2484         hash_free_strings(to_table);
2485         g_hash_table_destroy(to_table);
2486
2487         if (cc_list) {
2488                 for (cur = cc_list; cur != NULL; cur = cur->next)
2489                         compose_entry_append(compose, (gchar *)cur->data,
2490                                              COMPOSE_CC);
2491                 slist_free_strings(cc_list);
2492                 g_slist_free(cc_list);
2493         }
2494
2495 }
2496
2497 #define SET_ENTRY(entry, str) \
2498 { \
2499         if (str && *str) \
2500                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
2501 }
2502
2503 #define SET_ADDRESS(type, str) \
2504 { \
2505         if (str && *str) \
2506                 compose_entry_append(compose, str, type); \
2507 }
2508
2509 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
2510 {
2511         g_return_if_fail(msginfo != NULL);
2512
2513         SET_ENTRY(subject_entry, msginfo->subject);
2514         SET_ADDRESS(COMPOSE_TO, msginfo->to);
2515         SET_ADDRESS(COMPOSE_CC, compose->cc);
2516         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
2517         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
2518         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
2519         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2520
2521         compose_update_priority_menu_item(compose);
2522         compose_update_privacy_system_menu_item(compose, FALSE);
2523         compose_show_first_last_header(compose, TRUE);
2524 }
2525
2526 #undef SET_ENTRY
2527 #undef SET_ADDRESS
2528
2529 static void compose_insert_sig(Compose *compose, gboolean replace)
2530 {
2531         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2532         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2533         GtkTextMark *mark;
2534         GtkTextIter iter, iter_end;
2535         gint cur_pos;
2536         gboolean prev_autowrap;
2537
2538         
2539         g_return_if_fail(compose->account != NULL);
2540
2541         prev_autowrap = compose->autowrap;
2542         compose->autowrap = FALSE;
2543
2544         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2545                                         G_CALLBACK(compose_changed_cb),
2546                                         compose);
2547         
2548         mark = gtk_text_buffer_get_insert(buffer);
2549         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2550         cur_pos = gtk_text_iter_get_offset (&iter);
2551
2552         gtk_text_buffer_get_end_iter(buffer, &iter);
2553
2554         if (replace && compose->sig_str) {
2555                 gboolean found;
2556                 GtkTextIter first_iter, start_iter, end_iter;
2557
2558                 gtk_text_buffer_get_start_iter(buffer, &first_iter);
2559
2560                 if (compose->sig_str[0] == '\0')
2561                         found = FALSE;
2562                 else
2563                         found = gtk_text_iter_forward_search(&first_iter,
2564                                                              compose->sig_str,
2565                                                              GTK_TEXT_SEARCH_TEXT_ONLY,
2566                                                              &start_iter, &end_iter,
2567                                                              NULL);
2568
2569                 if (found) {
2570                         gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
2571                         iter = start_iter;
2572                 }
2573         }
2574
2575         g_free(compose->sig_str);
2576         compose->sig_str = compose_get_signature_str(compose);
2577         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2578                 compose->sig_str = g_strdup("");
2579
2580         cur_pos = gtk_text_iter_get_offset(&iter);
2581         gtk_text_buffer_insert(buffer, &iter, compose->sig_str, -1);
2582         /* skip \n\n */
2583         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2584         gtk_text_iter_forward_char(&iter);
2585         gtk_text_iter_forward_char(&iter);
2586         gtk_text_buffer_get_end_iter(buffer, &iter_end);
2587         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &iter_end);
2588
2589         if (cur_pos > gtk_text_buffer_get_char_count (buffer))
2590                 cur_pos = gtk_text_buffer_get_char_count (buffer);
2591
2592         /* put the cursor where it should be 
2593          * either where the quote_fmt says, either before the signature */
2594         if (compose->set_cursor_pos < 0)
2595                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2596         else
2597                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, 
2598                         compose->set_cursor_pos);
2599                 
2600         gtk_text_buffer_place_cursor(buffer, &iter);
2601         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2602                                         G_CALLBACK(compose_changed_cb),
2603                                         compose);
2604                 
2605         compose->autowrap = prev_autowrap;
2606         if (compose->autowrap)
2607                 compose_wrap_all(compose);
2608 }
2609
2610 static gchar *compose_get_signature_str(Compose *compose)
2611 {
2612         gchar *sig_body = NULL;
2613         gchar *sig_str = NULL;
2614         gchar *utf8_sig_str = NULL;
2615
2616         g_return_val_if_fail(compose->account != NULL, NULL);
2617
2618         if (!compose->account->sig_path)
2619                 return NULL;
2620
2621         if (compose->account->sig_type == SIG_FILE) {
2622                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2623                         g_warning("can't open signature file: %s\n",
2624                                   compose->account->sig_path);
2625                         return NULL;
2626                 }
2627         }
2628
2629         if (compose->account->sig_type == SIG_COMMAND)
2630                 sig_body = get_command_output(compose->account->sig_path);
2631         else {
2632                 gchar *tmp;
2633
2634                 tmp = file_read_to_str(compose->account->sig_path);
2635                 if (!tmp)
2636                         return NULL;
2637                 sig_body = normalize_newlines(tmp);
2638                 g_free(tmp);
2639         }
2640
2641         if (compose->account->sig_sep) {
2642                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2643                                       NULL);
2644                 g_free(sig_body);
2645         } else
2646                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2647
2648         if (sig_str) {
2649                 if (g_utf8_validate(sig_str, -1, NULL) == TRUE)
2650                         utf8_sig_str = sig_str;
2651                 else {
2652                         utf8_sig_str = conv_codeset_strdup
2653                                 (sig_str, conv_get_locale_charset_str(),
2654                                  CS_INTERNAL);
2655                         g_free(sig_str);
2656                 }
2657         }
2658
2659         return utf8_sig_str;
2660 }
2661
2662 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2663 {
2664         GtkTextView *text;
2665         GtkTextBuffer *buffer;
2666         GtkTextMark *mark;
2667         GtkTextIter iter;
2668         const gchar *cur_encoding;
2669         gchar buf[BUFFSIZE];
2670         gint len;
2671         FILE *fp;
2672         gboolean prev_autowrap;
2673         gboolean badtxt = FALSE;
2674
2675         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2676
2677         if ((fp = g_fopen(file, "rb")) == NULL) {
2678                 FILE_OP_ERROR(file, "fopen");
2679                 return COMPOSE_INSERT_READ_ERROR;
2680         }
2681
2682         prev_autowrap = compose->autowrap;
2683         compose->autowrap = FALSE;
2684
2685         text = GTK_TEXT_VIEW(compose->text);
2686         buffer = gtk_text_view_get_buffer(text);
2687         mark = gtk_text_buffer_get_insert(buffer);
2688         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2689
2690         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2691                                         G_CALLBACK(text_inserted),
2692                                         compose);
2693
2694         cur_encoding = conv_get_locale_charset_str();
2695
2696         while (fgets(buf, sizeof(buf), fp) != NULL) {
2697                 gchar *str;
2698
2699                 if (g_utf8_validate(buf, -1, NULL) == TRUE)
2700                         str = g_strdup(buf);
2701                 else
2702                         str = conv_codeset_strdup
2703                                 (buf, cur_encoding, CS_INTERNAL);
2704                 if (!str) continue;
2705
2706                 /* strip <CR> if DOS/Windows file,
2707                    replace <CR> with <LF> if Macintosh file. */
2708                 strcrchomp(str);
2709                 len = strlen(str);
2710                 if (len > 0 && str[len - 1] != '\n') {
2711                         while (--len >= 0)
2712                                 if (str[len] == '\r') str[len] = '\n';
2713                 }
2714
2715                 gtk_text_buffer_insert(buffer, &iter, str, -1);
2716                 g_free(str);
2717         }
2718
2719         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2720                                           G_CALLBACK(text_inserted),
2721                                           compose);
2722         compose->autowrap = prev_autowrap;
2723         if (compose->autowrap)
2724                 compose_wrap_all(compose);
2725
2726         fclose(fp);
2727
2728         if (badtxt)
2729                 return COMPOSE_INSERT_INVALID_CHARACTER;
2730         else 
2731                 return COMPOSE_INSERT_SUCCESS;
2732 }
2733
2734 static void compose_attach_append(Compose *compose, const gchar *file,
2735                                   const gchar *filename,
2736                                   const gchar *content_type)
2737 {
2738         AttachInfo *ainfo;
2739         GtkTreeIter iter;
2740         FILE *fp;
2741         off_t size;
2742         GAuto *auto_ainfo;
2743         gchar *size_text;
2744         GtkListStore *store;
2745         gchar *name;
2746         gboolean has_binary = FALSE;
2747
2748         if (!is_file_exist(file)) {
2749                 g_warning("File %s doesn't exist\n", filename);
2750                 return;
2751         }
2752         if ((size = get_file_size(file)) < 0) {
2753                 g_warning("Can't get file size of %s\n", filename);
2754                 return;
2755         }
2756         if (size == 0) {
2757                 alertpanel_notice(_("File %s is empty."), filename);
2758                 return;
2759         }
2760         if ((fp = g_fopen(file, "rb")) == NULL) {
2761                 alertpanel_error(_("Can't read %s."), filename);
2762                 return;
2763         }
2764         fclose(fp);
2765
2766         ainfo = g_new0(AttachInfo, 1);
2767         auto_ainfo = g_auto_pointer_new_with_free
2768                         (ainfo, (GFreeFunc) compose_attach_info_free); 
2769         ainfo->file = g_strdup(file);
2770
2771         if (content_type) {
2772                 ainfo->content_type = g_strdup(content_type);
2773                 if (!g_ascii_strcasecmp(content_type, "message/rfc822")) {
2774                         MsgInfo *msginfo;
2775                         MsgFlags flags = {0, 0};
2776
2777                         if (procmime_get_encoding_for_text_file(file, &has_binary) == ENC_7BIT)
2778                                 ainfo->encoding = ENC_7BIT;
2779                         else
2780                                 ainfo->encoding = ENC_8BIT;
2781
2782                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2783                         if (msginfo && msginfo->subject)
2784                                 name = g_strdup(msginfo->subject);
2785                         else
2786                                 name = g_path_get_basename(filename ? filename : file);
2787
2788                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2789
2790                         procmsg_msginfo_free(msginfo);
2791                 } else {
2792                         if (!g_ascii_strncasecmp(content_type, "text", 4))
2793                                 ainfo->encoding = procmime_get_encoding_for_text_file(file, &has_binary);
2794                         else
2795                                 ainfo->encoding = ENC_BASE64;
2796                         name = g_path_get_basename(filename ? filename : file);
2797                         ainfo->name = g_strdup(name);
2798                 }
2799                 g_free(name);
2800         } else {
2801                 ainfo->content_type = procmime_get_mime_type(file);
2802                 if (!ainfo->content_type) {
2803                         ainfo->content_type =
2804                                 g_strdup("application/octet-stream");
2805                         ainfo->encoding = ENC_BASE64;
2806                 } else if (!g_ascii_strncasecmp(ainfo->content_type, "text", 4))
2807                         ainfo->encoding =
2808                                 procmime_get_encoding_for_text_file(file, &has_binary);
2809                 else
2810                         ainfo->encoding = ENC_BASE64;
2811                 name = g_path_get_basename(filename ? filename : file);
2812                 ainfo->name = g_strdup(name);   
2813                 g_free(name);
2814         }
2815
2816         if (!strcmp(ainfo->content_type, "unknown") || has_binary) {
2817                 g_free(ainfo->content_type);
2818                 ainfo->content_type = g_strdup("application/octet-stream");
2819         }
2820
2821         ainfo->size = size;
2822         size_text = to_human_readable(size);
2823
2824         store = GTK_LIST_STORE(gtk_tree_view_get_model
2825                         (GTK_TREE_VIEW(compose->attach_clist)));
2826                 
2827         gtk_list_store_append(store, &iter);
2828         gtk_list_store_set(store, &iter, 
2829                            COL_MIMETYPE, ainfo->content_type,
2830                            COL_SIZE, size_text,
2831                            COL_NAME, ainfo->name,
2832                            COL_DATA, ainfo,
2833                            COL_AUTODATA, auto_ainfo,
2834                            -1);
2835         
2836         g_auto_pointer_free(auto_ainfo);
2837 }
2838
2839 static void compose_use_signing(Compose *compose, gboolean use_signing)
2840 {
2841         GtkItemFactory *ifactory;
2842         GtkWidget *menuitem = NULL;
2843
2844         compose->use_signing = use_signing;
2845         ifactory = gtk_item_factory_from_widget(compose->menubar);
2846         menuitem = gtk_item_factory_get_item
2847                 (ifactory, "/Options/Sign");
2848         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2849                                        use_signing);
2850 }
2851
2852 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2853 {
2854         GtkItemFactory *ifactory;
2855         GtkWidget *menuitem = NULL;
2856
2857         compose->use_encryption = use_encryption;
2858         ifactory = gtk_item_factory_from_widget(compose->menubar);
2859         menuitem = gtk_item_factory_get_item
2860                 (ifactory, "/Options/Encrypt");
2861
2862         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2863                                        use_encryption);
2864 }
2865
2866 #define NEXT_PART_NOT_CHILD(info)  \
2867 {  \
2868         node = info->node;  \
2869         while (node->children)  \
2870                 node = g_node_last_child(node);  \
2871         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2872 }
2873
2874 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2875 {
2876         MimeInfo *mimeinfo;
2877         MimeInfo *child;
2878         MimeInfo *firsttext = NULL;
2879         MimeInfo *encrypted = NULL;
2880         GNode    *node;
2881         gchar *outfile;
2882         const gchar *partname = NULL;
2883
2884         mimeinfo = procmime_scan_message(msginfo);
2885         if (!mimeinfo) return;
2886
2887         if (mimeinfo->node->children == NULL) {
2888                 procmime_mimeinfo_free_all(mimeinfo);
2889                 return;
2890         }
2891
2892         /* find first content part */
2893         child = (MimeInfo *) mimeinfo->node->children->data;
2894         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2895                 child = (MimeInfo *)child->node->children->data;
2896
2897         if (child->type == MIMETYPE_TEXT) {
2898                 firsttext = child;
2899                 debug_print("First text part found\n");
2900         } else if (compose->mode == COMPOSE_REEDIT &&
2901                  child->type == MIMETYPE_APPLICATION &&
2902                  !g_ascii_strcasecmp(child->subtype, "pgp-encrypted")) {
2903                 encrypted = (MimeInfo *)child->node->parent->data;
2904         }
2905      
2906         child = (MimeInfo *) mimeinfo->node->children->data;
2907         while (child != NULL) {
2908                 if (child == encrypted) {
2909                         /* skip this part of tree */
2910                         NEXT_PART_NOT_CHILD(child);
2911                         continue;
2912                 }
2913
2914                 if (child->type == MIMETYPE_MULTIPART) {
2915                         /* get the actual content */
2916                         child = procmime_mimeinfo_next(child);
2917                         continue;
2918                 }
2919                     
2920                 if (child == firsttext) {
2921                         child = procmime_mimeinfo_next(child);
2922                         continue;
2923                 }
2924
2925                 outfile = procmime_get_tmp_file_name(child);
2926                 if (procmime_get_part(outfile, child) < 0)
2927                         g_warning("Can't get the part of multipart message.");
2928                 else {
2929                         gchar *content_type;
2930
2931                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2932
2933                         /* if we meet a pgp signature, we don't attach it, but
2934                          * we force signing. */
2935                         if (strcmp(content_type, "application/pgp-signature")) {
2936                                 partname = procmime_mimeinfo_get_parameter(child, "filename");
2937                                 if (partname == NULL)
2938                                         partname = procmime_mimeinfo_get_parameter(child, "name");
2939                                 if (partname == NULL)
2940                                         partname = "";
2941                                 compose_attach_append(compose, outfile, 
2942                                                       partname, content_type);
2943                         } else {
2944                                 compose_force_signing(compose, compose->account);
2945                         }
2946                         g_free(content_type);
2947                 }
2948                 g_free(outfile);
2949                 NEXT_PART_NOT_CHILD(child);
2950         }
2951         procmime_mimeinfo_free_all(mimeinfo);
2952 }
2953
2954 #undef NEXT_PART_NOT_CHILD
2955
2956
2957
2958 typedef enum {
2959         WAIT_FOR_INDENT_CHAR,
2960         WAIT_FOR_INDENT_CHAR_OR_SPACE,
2961 } IndentState;
2962
2963 /* return indent length, we allow:
2964    indent characters followed by indent characters or spaces/tabs,
2965    alphabets and numbers immediately followed by indent characters,
2966    and the repeating sequences of the above
2967    If quote ends with multiple spaces, only the first one is included. */
2968 static gchar *compose_get_quote_str(GtkTextBuffer *buffer,
2969                                     const GtkTextIter *start, gint *len)
2970 {
2971         GtkTextIter iter = *start;
2972         gunichar wc;
2973         gchar ch[6];
2974         gint clen;
2975         IndentState state = WAIT_FOR_INDENT_CHAR;
2976         gboolean is_space;
2977         gboolean is_indent;
2978         gint alnum_count = 0;
2979         gint space_count = 0;
2980         gint quote_len = 0;
2981
2982         if (prefs_common.quote_chars == NULL) {
2983                 return 0 ;
2984         }
2985
2986         while (!gtk_text_iter_ends_line(&iter)) {
2987                 wc = gtk_text_iter_get_char(&iter);
2988                 if (g_unichar_iswide(wc))
2989                         break;
2990                 clen = g_unichar_to_utf8(wc, ch);
2991                 if (clen != 1)
2992                         break;
2993
2994                 is_indent = strchr(prefs_common.quote_chars, ch[0]) ? TRUE : FALSE;
2995                 is_space = g_unichar_isspace(wc);
2996
2997                 if (state == WAIT_FOR_INDENT_CHAR) {
2998                         if (!is_indent && !g_unichar_isalnum(wc))
2999                                 break;
3000                         if (is_indent) {
3001                                 quote_len += alnum_count + space_count + 1;
3002                                 alnum_count = space_count = 0;
3003                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
3004                         } else
3005                                 alnum_count++;
3006                 } else if (state == WAIT_FOR_INDENT_CHAR_OR_SPACE) {
3007                         if (!is_indent && !is_space && !g_unichar_isalnum(wc))
3008                                 break;
3009                         if (is_space)
3010                                 space_count++;
3011                         else if (is_indent) {
3012                                 quote_len += alnum_count + space_count + 1;
3013                                 alnum_count = space_count = 0;
3014                         } else {
3015                                 alnum_count++;
3016                                 state = WAIT_FOR_INDENT_CHAR;
3017                         }
3018                 }
3019
3020                 gtk_text_iter_forward_char(&iter);
3021         }
3022
3023         if (quote_len > 0 && space_count > 0)
3024                 quote_len++;
3025
3026         if (len)
3027                 *len = quote_len;
3028
3029         if (quote_len > 0) {
3030                 iter = *start;
3031                 gtk_text_iter_forward_chars(&iter, quote_len);
3032                 return gtk_text_buffer_get_text(buffer, start, &iter, FALSE);
3033         }
3034
3035         return NULL;
3036 }
3037
3038 /* return TRUE if the line is itemized */
3039 static gboolean compose_is_itemized(GtkTextBuffer *buffer,
3040                                     const GtkTextIter *start)
3041 {
3042         GtkTextIter iter = *start;
3043         gunichar wc;
3044         gchar ch[6];
3045         gint clen;
3046
3047         if (gtk_text_iter_ends_line(&iter))
3048                 return FALSE;
3049
3050         while (1) {
3051                 wc = gtk_text_iter_get_char(&iter);
3052                 if (!g_unichar_isspace(wc))
3053                         break;
3054                 gtk_text_iter_forward_char(&iter);
3055                 if (gtk_text_iter_ends_line(&iter))
3056                         return FALSE;
3057         }
3058
3059         clen = g_unichar_to_utf8(wc, ch);
3060         if (clen != 1)
3061                 return FALSE;
3062
3063         if (!strchr("*-+", ch[0]))
3064                 return FALSE;
3065
3066         gtk_text_iter_forward_char(&iter);
3067         if (gtk_text_iter_ends_line(&iter))
3068                 return FALSE;
3069         wc = gtk_text_iter_get_char(&iter);
3070         if (g_unichar_isspace(wc))
3071                 return TRUE;
3072
3073         return FALSE;
3074 }
3075
3076 static gboolean compose_get_line_break_pos(GtkTextBuffer *buffer,
3077                                            const GtkTextIter *start,
3078                                            GtkTextIter *break_pos,
3079                                            gint max_col,
3080                                            gint quote_len)
3081 {
3082         GtkTextIter iter = *start, line_end = *start;
3083         PangoLogAttr *attrs;
3084         gchar *str;
3085         gchar *p;
3086         gint len;
3087         gint i;
3088         gint col = 0;
3089         gint pos = 0;
3090         gboolean can_break = FALSE;
3091         gboolean do_break = FALSE;
3092         gboolean was_white = FALSE;
3093         gboolean prev_dont_break = FALSE;
3094
3095         gtk_text_iter_forward_to_line_end(&line_end);
3096         str = gtk_text_buffer_get_text(buffer, &iter, &line_end, FALSE);
3097         len = g_utf8_strlen(str, -1);
3098         /* g_print("breaking line: %d: %s (len = %d)\n",
3099                 gtk_text_iter_get_line(&iter), str, len); */
3100         attrs = g_new(PangoLogAttr, len + 1);
3101
3102         pango_default_break(str, -1, NULL, attrs, len + 1);
3103
3104         p = str;
3105
3106         /* skip quote and leading spaces */
3107         for (i = 0; *p != '\0' && i < len; i++) {
3108                 gunichar wc;
3109
3110                 wc = g_utf8_get_char(p);
3111                 if (i >= quote_len && !g_unichar_isspace(wc))
3112                         break;
3113                 if (g_unichar_iswide(wc))
3114                         col += 2;
3115                 else if (*p == '\t')
3116                         col += 8;
3117                 else
3118                         col++;
3119                 p = g_utf8_next_char(p);
3120         }
3121
3122         for (; *p != '\0' && i < len; i++) {
3123                 PangoLogAttr *attr = attrs + i;
3124                 gunichar wc;
3125                 gint uri_len;
3126
3127                 if (attr->is_line_break && can_break && was_white && !prev_dont_break)
3128                         pos = i;
3129                 
3130                 was_white = attr->is_white;
3131
3132                 /* don't wrap URI */
3133                 if ((uri_len = get_uri_len(p)) > 0) {
3134                         col += uri_len;
3135                         if (pos > 0 && col > max_col) {
3136                                 do_break = TRUE;
3137                                 break;
3138                         }
3139                         i += uri_len - 1;
3140                         p += uri_len;
3141                         can_break = TRUE;
3142                         continue;
3143                 }
3144
3145                 wc = g_utf8_get_char(p);
3146                 if (g_unichar_iswide(wc)) {
3147                         col += 2;
3148                         if (prev_dont_break && can_break && attr->is_line_break)
3149                                 pos = i;
3150                 } else if (*p == '\t')
3151                         col += 8;
3152                 else
3153                         col++;
3154                 if (pos > 0 && col > max_col) {
3155                         do_break = TRUE;
3156                         break;
3157                 }
3158
3159                 if (*p == '-' || *p == '/')
3160                         prev_dont_break = TRUE;
3161                 else
3162                         prev_dont_break = FALSE;
3163
3164                 p = g_utf8_next_char(p);
3165                 can_break = TRUE;
3166         }
3167
3168         debug_print("compose_get_line_break_pos(): do_break = %d, pos = %d, col = %d\n", do_break, pos, col);
3169
3170         g_free(attrs);
3171         g_free(str);
3172
3173         *break_pos = *start;
3174         gtk_text_iter_set_line_offset(break_pos, pos);
3175
3176         return do_break;
3177 }
3178
3179 static gboolean compose_join_next_line(Compose *compose,
3180                                        GtkTextBuffer *buffer,
3181                                        GtkTextIter *iter,
3182                                        const gchar *quote_str)
3183 {
3184         GtkTextIter iter_ = *iter, cur, prev, next, end;
3185         PangoLogAttr attrs[3];
3186         gchar *str;
3187         gchar *next_quote_str;
3188         gunichar wc1, wc2;
3189         gint quote_len;
3190         gboolean keep_cursor = FALSE;
3191
3192         if (!gtk_text_iter_forward_line(&iter_) ||
3193             gtk_text_iter_ends_line(&iter_))
3194                 return FALSE;
3195
3196         next_quote_str = compose_get_quote_str(buffer, &iter_, &quote_len);
3197
3198         if ((quote_str || next_quote_str) &&
3199             strcmp2(quote_str, next_quote_str) != 0) {
3200                 g_free(next_quote_str);
3201                 return FALSE;
3202         }
3203         g_free(next_quote_str);
3204
3205         end = iter_;
3206         if (quote_len > 0) {
3207                 gtk_text_iter_forward_chars(&end, quote_len);
3208                 if (gtk_text_iter_ends_line(&end))
3209                         return FALSE;
3210         }
3211
3212         /* don't join itemized lines */
3213         if (compose_is_itemized(buffer, &end))
3214                 return FALSE;
3215
3216         /* don't join signature separator */
3217         if (compose_is_sig_separator(compose, buffer, &iter_))
3218                 return FALSE;
3219
3220         /* delete quote str */
3221         if (quote_len > 0)
3222                 gtk_text_buffer_delete(buffer, &iter_, &end);
3223
3224         /* don't join line breaks put by the user */
3225         prev = cur = iter_;
3226         gtk_text_iter_backward_char(&cur);
3227         if (gtk_text_iter_has_tag(&cur, compose->no_join_tag)) {
3228                 gtk_text_iter_forward_char(&cur);
3229                 *iter = cur;
3230                 return FALSE;
3231         }
3232         gtk_text_iter_forward_char(&cur);
3233         /* delete linebreak and extra spaces */
3234         while (gtk_text_iter_backward_char(&cur)) {
3235                 wc1 = gtk_text_iter_get_char(&cur);
3236                 if (!g_unichar_isspace(wc1))
3237                         break;
3238                 prev = cur;
3239         }
3240         next = cur = iter_;
3241         while (!gtk_text_iter_ends_line(&cur)) {
3242                 wc1 = gtk_text_iter_get_char(&cur);
3243                 if (!g_unichar_isspace(wc1))
3244                         break;
3245                 gtk_text_iter_forward_char(&cur);
3246                 next = cur;
3247         }
3248         if (!gtk_text_iter_equal(&prev, &next)) {
3249                 GtkTextMark *mark;
3250
3251                 mark = gtk_text_buffer_get_insert(buffer);
3252                 gtk_text_buffer_get_iter_at_mark(buffer, &cur, mark);
3253                 if (gtk_text_iter_equal(&prev, &cur))
3254                         keep_cursor = TRUE;
3255                 gtk_text_buffer_delete(buffer, &prev, &next);
3256         }
3257         iter_ = prev;
3258
3259         /* insert space if required */
3260         gtk_text_iter_backward_char(&prev);
3261         wc1 = gtk_text_iter_get_char(&prev);
3262         wc2 = gtk_text_iter_get_char(&next);
3263         gtk_text_iter_forward_char(&next);
3264         str = gtk_text_buffer_get_text(buffer, &prev, &next, FALSE);
3265         pango_default_break(str, -1, NULL, attrs, 3);
3266         if (!attrs[1].is_line_break ||
3267             (!g_unichar_iswide(wc1) || !g_unichar_iswide(wc2))) {
3268                 gtk_text_buffer_insert(buffer, &iter_, " ", 1);
3269                 if (keep_cursor) {
3270                         gtk_text_iter_backward_char(&iter_);
3271                         gtk_text_buffer_place_cursor(buffer, &iter_);
3272                 }
3273         }
3274         g_free(str);
3275
3276         *iter = iter_;
3277         return TRUE;
3278 }
3279
3280 #define ADD_TXT_POS(bp_, ep_, pti_) \
3281         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
3282                 last = last->next; \
3283                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
3284                 last->next = NULL; \
3285         } else { \
3286                 g_warning("alloc error scanning URIs\n"); \
3287         }
3288
3289 static gboolean automatic_break = FALSE;
3290 static void compose_beautify_paragraph(Compose *compose, GtkTextIter *par_iter, gboolean force)
3291 {
3292         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3293         GtkTextBuffer *buffer;
3294         GtkTextIter iter, break_pos, end_of_line;
3295         gchar *quote_str = NULL;
3296         gint quote_len;
3297         gboolean wrap_quote = prefs_common.linewrap_quote;
3298         gboolean prev_autowrap = compose->autowrap;
3299         gint startq_offset = -1, noq_offset = -1;
3300         gint uri_start = -1, uri_stop = -1;
3301         gint nouri_start = -1, nouri_stop = -1;
3302         gint num_blocks = 0;
3303
3304         compose->autowrap = FALSE;
3305
3306         buffer = gtk_text_view_get_buffer(text);
3307         undo_wrapping(compose->undostruct, TRUE);
3308         if (par_iter) {
3309                 iter = *par_iter;
3310         } else {
3311                 GtkTextMark *mark;
3312                 mark = gtk_text_buffer_get_insert(buffer);
3313                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
3314         }
3315
3316         /* move to paragraph start */
3317         gtk_text_iter_set_line_offset(&iter, 0);
3318         if (gtk_text_iter_ends_line(&iter)) {
3319                 while (gtk_text_iter_ends_line(&iter) &&
3320                        gtk_text_iter_forward_line(&iter))
3321                         ;
3322         } else {
3323                 while (gtk_text_iter_backward_line(&iter)) {
3324                         if (gtk_text_iter_ends_line(&iter)) {
3325                                 gtk_text_iter_forward_line(&iter);
3326                                 break;
3327                         }
3328                 }
3329         }
3330
3331         /* go until paragraph end (empty line) */
3332         
3333         while (!gtk_text_iter_ends_line(&iter)) {
3334                 gchar *scanpos = NULL;
3335                 /* parse table - in order of priority */
3336                 struct table {
3337                         const gchar *needle; /* token */
3338
3339                         /* token search function */
3340                         gchar    *(*search)     (const gchar *haystack,
3341                                                  const gchar *needle);
3342                         /* part parsing function */
3343                         gboolean  (*parse)      (const gchar *start,
3344                                                  const gchar *scanpos,
3345                                                  const gchar **bp_,
3346                                                  const gchar **ep_,
3347                                                  gboolean hdr);
3348                         /* part to URI function */
3349                         gchar    *(*build_uri)  (const gchar *bp,
3350                                                  const gchar *ep);
3351                 };
3352
3353                 static struct table parser[] = {
3354                         {"http://",  strcasestr, get_uri_part,   make_uri_string},
3355                         {"https://", strcasestr, get_uri_part,   make_uri_string},
3356                         {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
3357                         {"www.",     strcasestr, get_uri_part,   make_http_string},
3358                         {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
3359                         {"@",        strcasestr, get_email_part, make_email_string}
3360                 };
3361                 const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
3362                 gint last_index = PARSE_ELEMS;
3363                 gint  n;
3364                 gchar *o_walk = NULL, *walk = NULL, *bp = NULL, *ep = NULL;
3365                 gint walk_pos;
3366                 
3367                 if (!prev_autowrap && num_blocks == 0) {
3368                         num_blocks++;
3369                         g_signal_handlers_block_by_func(G_OBJECT(buffer),
3370                                         G_CALLBACK(text_inserted),
3371                                         compose);
3372                 }
3373                 if (gtk_text_iter_has_tag(&iter, compose->no_wrap_tag) && !force)
3374                         goto colorize;
3375
3376                 uri_start = uri_stop = -1;
3377                 quote_len = 0;
3378                 quote_str = compose_get_quote_str(buffer, &iter, &quote_len);
3379
3380                 if (quote_str) {
3381                         if (!wrap_quote) {
3382                                 if (startq_offset == -1) {
3383                                         startq_offset = gtk_text_iter_get_offset(&iter);
3384                                 }
3385                                 goto colorize;
3386                         }
3387                         debug_print("compose_beautify_paragraph(): quote_str = '%s'\n", quote_str);
3388                         if (startq_offset == -1) 
3389                                 startq_offset = gtk_text_iter_get_offset(&iter);
3390                 } else {
3391                         if (startq_offset == -1)
3392                                 noq_offset = gtk_text_iter_get_offset(&iter);
3393                 }
3394
3395                 if (prev_autowrap == FALSE && !force && !wrap_quote) {
3396                         goto colorize;
3397                 }
3398                 if (compose_get_line_break_pos(buffer, &iter, &break_pos,
3399                                                prefs_common.linewrap_len,
3400                                                quote_len)) {
3401                         GtkTextIter prev, next, cur;
3402                         
3403                         if (prev_autowrap != FALSE || force) {
3404                                 automatic_break = TRUE;
3405                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3406                                 automatic_break = FALSE;
3407                         } else if (quote_str && wrap_quote) {
3408                                 automatic_break = TRUE;
3409                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3410                                 automatic_break = FALSE;
3411                         } else 
3412                                 goto colorize;
3413                         /* remove trailing spaces */
3414                         cur = break_pos;
3415                         gtk_text_iter_backward_char(&cur);
3416                         prev = next = cur;
3417                         while (!gtk_text_iter_starts_line(&cur)) {
3418                                 gunichar wc;
3419
3420                                 gtk_text_iter_backward_char(&cur);
3421                                 wc = gtk_text_iter_get_char(&cur);
3422                                 if (!g_unichar_isspace(wc))
3423                                         break;
3424                                 prev = cur;
3425                         }
3426                         if (!gtk_text_iter_equal(&prev, &next)) {
3427                                 gtk_text_buffer_delete(buffer, &prev, &next);
3428                                 break_pos = next;
3429                                 gtk_text_iter_forward_char(&break_pos);
3430                         }
3431
3432                         if (quote_str)
3433                                 gtk_text_buffer_insert(buffer, &break_pos,
3434                                                        quote_str, -1);
3435
3436                         iter = break_pos;
3437                         compose_join_next_line(compose, buffer, &iter, quote_str);
3438
3439                         /* move iter to current line start */
3440                         gtk_text_iter_set_line_offset(&iter, 0);
3441                         if (quote_str) {
3442                                 g_free(quote_str);
3443                                 quote_str = NULL;
3444                         }
3445                         continue;
3446                 } else {
3447                         /* move iter to next line start */
3448                         iter = break_pos;
3449                 }
3450
3451 colorize:
3452                 if (!prev_autowrap && num_blocks > 0) {
3453                         num_blocks--;
3454                         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
3455                                         G_CALLBACK(text_inserted),
3456                                         compose);
3457                 }
3458                 end_of_line = iter;
3459                 while (!gtk_text_iter_ends_line(&end_of_line)) {
3460                         gtk_text_iter_forward_char(&end_of_line);
3461                 }
3462                 o_walk = walk = gtk_text_buffer_get_text(buffer, &iter, &end_of_line, FALSE);
3463
3464                 nouri_start = gtk_text_iter_get_offset(&iter);
3465                 nouri_stop = gtk_text_iter_get_offset(&end_of_line);
3466
3467                 walk_pos = gtk_text_iter_get_offset(&iter);
3468                 /* FIXME: this looks phony. scanning for anything in the parse table */
3469                 for (n = 0; n < PARSE_ELEMS; n++) {
3470                         gchar *tmp;
3471
3472                         tmp = parser[n].search(walk, parser[n].needle);
3473                         if (tmp) {
3474                                 if (scanpos == NULL || tmp < scanpos) {
3475                                         scanpos = tmp;
3476                                         last_index = n;
3477                                 }
3478                         }                                       
3479                 }
3480
3481                 bp = ep = 0;
3482                 if (scanpos) {
3483                         /* check if URI can be parsed */
3484                         if (parser[last_index].parse(walk, scanpos, (const gchar **)&bp,
3485                                         (const gchar **)&ep, FALSE)
3486                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
3487                                         walk = ep;
3488                         } else
3489                                 walk = scanpos +
3490                                         strlen(parser[last_index].needle);
3491                 } 
3492                 if (bp && ep) {
3493                         uri_start = walk_pos + (bp - o_walk);
3494                         uri_stop  = walk_pos + (ep - o_walk);
3495                 }
3496                 g_free(o_walk);
3497                 o_walk = NULL;
3498                 gtk_text_iter_forward_line(&iter);
3499                 g_free(quote_str);
3500                 quote_str = NULL;
3501                 if (startq_offset != -1) {
3502                         GtkTextIter startquote, endquote;
3503                         gtk_text_buffer_get_iter_at_offset(
3504                                 buffer, &startquote, startq_offset);
3505                         endquote = iter;
3506                         gtk_text_buffer_apply_tag_by_name(
3507                                 buffer, "quote", &startquote, &endquote);
3508                         startq_offset = -1;
3509                 } else if (noq_offset != -1) {
3510                         GtkTextIter startnoquote, endnoquote;
3511                         gtk_text_buffer_get_iter_at_offset(
3512                                 buffer, &startnoquote, noq_offset);
3513                         endnoquote = iter;
3514                         gtk_text_buffer_remove_tag_by_name(
3515                                 buffer, "quote", &startnoquote, &endnoquote);
3516                         noq_offset = -1;
3517                 }
3518                 
3519                 /* always */ {
3520                         GtkTextIter nouri_start_iter, nouri_end_iter;
3521                         gtk_text_buffer_get_iter_at_offset(
3522                                 buffer, &nouri_start_iter, nouri_start);
3523                         gtk_text_buffer_get_iter_at_offset(
3524                                 buffer, &nouri_end_iter, nouri_stop);
3525                         gtk_text_buffer_remove_tag_by_name(
3526                                 buffer, "link", &nouri_start_iter, &nouri_end_iter);
3527                 }
3528                 if (uri_start > 0 && uri_stop > 0) {
3529                         GtkTextIter uri_start_iter, uri_end_iter;
3530                         gtk_text_buffer_get_iter_at_offset(
3531                                 buffer, &uri_start_iter, uri_start);
3532                         gtk_text_buffer_get_iter_at_offset(
3533                                 buffer, &uri_end_iter, uri_stop);
3534                         gtk_text_buffer_apply_tag_by_name(
3535                                 buffer, "link", &uri_start_iter, &uri_end_iter);
3536                 }
3537         }
3538
3539         if (par_iter)
3540                 *par_iter = iter;
3541         undo_wrapping(compose->undostruct, FALSE);
3542         compose->autowrap = prev_autowrap;
3543 }
3544
3545 void compose_action_cb(void *data)
3546 {
3547         Compose *compose = (Compose *)data;
3548         compose_wrap_all(compose);
3549 }
3550
3551 static void compose_wrap_all(Compose *compose)
3552 {
3553         compose_wrap_all_full(compose, FALSE);
3554 }
3555
3556 static void compose_wrap_all_full(Compose *compose, gboolean force)
3557 {
3558         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3559         GtkTextBuffer *buffer;
3560         GtkTextIter iter;
3561
3562         buffer = gtk_text_view_get_buffer(text);
3563
3564         gtk_text_buffer_get_start_iter(buffer, &iter);
3565         while (!gtk_text_iter_is_end(&iter))
3566                 compose_beautify_paragraph(compose, &iter, force);
3567
3568 }
3569
3570 static void compose_set_title(Compose *compose)
3571 {
3572         gchar *str;
3573         gchar *edited;
3574         gchar *subject;
3575         
3576         edited = compose->modified ? _(" [Edited]") : "";
3577         
3578         subject = gtk_editable_get_chars(
3579                         GTK_EDITABLE(compose->subject_entry), 0, -1);
3580
3581         if (subject && strlen(subject))
3582                 str = g_strdup_printf(_("%s - Compose message%s"),
3583                                       subject, edited); 
3584         else
3585                 str = g_strdup_printf(_("[no subject] - Compose message%s"), edited);
3586         gtk_window_set_title(GTK_WINDOW(compose->window), str);
3587         g_free(str);
3588         g_free(subject);
3589 }
3590
3591 /**
3592  * compose_current_mail_account:
3593  * 
3594  * Find a current mail account (the currently selected account, or the
3595  * default account, if a news account is currently selected).  If a
3596  * mail account cannot be found, display an error message.
3597  * 
3598  * Return value: Mail account, or NULL if not found.
3599  **/
3600 static PrefsAccount *
3601 compose_current_mail_account(void)
3602 {
3603         PrefsAccount *ac;
3604
3605         if (cur_account && cur_account->protocol != A_NNTP)
3606                 ac = cur_account;
3607         else {
3608                 ac = account_get_default();
3609                 if (!ac || ac->protocol == A_NNTP) {
3610                         alertpanel_error(_("Account for sending mail is not specified.\n"
3611                                            "Please select a mail account before sending."));
3612                         return NULL;
3613                 }
3614         }
3615         return ac;
3616 }
3617
3618 static void compose_select_account(Compose *compose, PrefsAccount *account,
3619                                    gboolean init)
3620 {
3621         GtkItemFactory *ifactory;
3622
3623         g_return_if_fail(account != NULL);
3624
3625         compose->account = account;
3626
3627         compose_set_title(compose);
3628
3629         ifactory = gtk_item_factory_from_widget(compose->menubar);
3630
3631         if (account->default_sign && compose->mode != COMPOSE_REDIRECT)
3632                 menu_set_active(ifactory, "/Options/Sign", TRUE);
3633         else
3634                 menu_set_active(ifactory, "/Options/Sign", FALSE);
3635         if (account->default_encrypt && compose->mode != COMPOSE_REDIRECT)
3636                 menu_set_active(ifactory, "/Options/Encrypt", TRUE);
3637         else
3638                 menu_set_active(ifactory, "/Options/Encrypt", FALSE);
3639                                        
3640         activate_privacy_system(compose, account, FALSE);
3641
3642         if (!init && compose->mode != COMPOSE_REDIRECT)
3643                 compose_insert_sig(compose, TRUE);
3644 }
3645
3646 gboolean compose_check_for_valid_recipient(Compose *compose) {
3647         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
3648         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
3649         gboolean recipient_found = FALSE;
3650         GSList *list;
3651         gchar **strptr;
3652
3653         /* free to and newsgroup list */
3654         slist_free_strings(compose->to_list);
3655         g_slist_free(compose->to_list);
3656         compose->to_list = NULL;
3657                         
3658         slist_free_strings(compose->newsgroup_list);
3659         g_slist_free(compose->newsgroup_list);
3660         compose->newsgroup_list = NULL;
3661
3662         /* search header entries for to and newsgroup entries */
3663         for (list = compose->header_list; list; list = list->next) {
3664                 gchar *header;
3665                 gchar *entry;
3666                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3667                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3668                 g_strstrip(entry);
3669                 if (entry[0] != '\0') {
3670                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
3671                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3672                                         compose->to_list = address_list_append(compose->to_list, entry);
3673                                         recipient_found = TRUE;
3674                                 }
3675                         }
3676                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
3677                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3678                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
3679                                         recipient_found = TRUE;
3680                                 }
3681                         }
3682                 }
3683                 g_free(header);
3684                 g_free(entry);
3685         }
3686         return recipient_found;
3687 }
3688
3689 static gboolean compose_check_for_set_recipients(Compose *compose)
3690 {
3691         if (compose->account->set_autocc && compose->account->auto_cc) {
3692                 gboolean found_other = FALSE;
3693                 GSList *list;
3694                 /* search header entries for to and newsgroup entries */
3695                 for (list = compose->header_list; list; list = list->next) {
3696                         gchar *entry;
3697                         gchar *header;
3698                         entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3699                         header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3700                         g_strstrip(entry);
3701                         if (strcmp(entry, compose->account->auto_cc)
3702                         ||  strcmp(header, (prefs_common.trans_hdr ? gettext("Cc:") : "Cc:"))) {
3703                                 found_other = TRUE;
3704                                 g_free(entry);
3705                                 break;
3706                         }
3707                         g_free(entry);
3708                         g_free(header);
3709                 }
3710                 if (!found_other) {
3711                         AlertValue aval;
3712                         aval = alertpanel(_("Send"),
3713                                           _("The only recipient is the default CC address. Send anyway?"),
3714                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3715                         if (aval != G_ALERTALTERNATE)
3716                                 return FALSE;
3717                 }
3718         }
3719         if (compose->account->set_autobcc && compose->account->auto_bcc) {
3720                 gboolean found_other = FALSE;
3721                 GSList *list;
3722                 /* search header entries for to and newsgroup entries */
3723                 for (list = compose->header_list; list; list = list->next) {
3724                         gchar *entry;
3725                         gchar *header;
3726                         entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3727                         header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3728                         g_strstrip(entry);
3729                         if (strcmp(entry, compose->account->auto_cc)
3730                         ||  strcmp(header, (prefs_common.trans_hdr ? gettext("Bcc:") : "Bcc:"))) {
3731                                 found_other = TRUE;
3732                                 g_free(entry);
3733                                 break;
3734                         }
3735                         g_free(entry);
3736                         g_free(header);
3737                 }
3738                 if (!found_other) {
3739                         AlertValue aval;
3740                         aval = alertpanel(_("Send"),
3741                                           _("The only recipient is the default BCC address. Send anyway?"),
3742                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3743                         if (aval != G_ALERTALTERNATE)
3744                                 return FALSE;
3745                 }
3746         }
3747         return TRUE;
3748 }
3749
3750 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
3751 {
3752         const gchar *str;
3753
3754         if (compose_check_for_valid_recipient(compose) == FALSE) {
3755                 alertpanel_error(_("Recipient is not specified."));
3756                 return FALSE;
3757         }
3758
3759         if (compose_check_for_set_recipients(compose) == FALSE) {
3760                 return FALSE;
3761         }
3762
3763         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3764         if (*str == '\0' && check_subject == TRUE) {
3765                 AlertValue aval;
3766
3767                 aval = alertpanel(_("Send"),
3768                                   _("Subject is empty. Send it anyway?"),
3769                                   GTK_STOCK_CANCEL, _("+_Send"), NULL);
3770                 if (aval != G_ALERTALTERNATE)
3771                         return FALSE;
3772         }
3773
3774         return TRUE;
3775 }
3776
3777 gint compose_send(Compose *compose)
3778 {
3779         gint msgnum;
3780         FolderItem *folder;
3781         gint val = -1;
3782         gchar *msgpath = NULL;
3783
3784         compose_allow_user_actions (compose, FALSE);
3785         compose->sending = TRUE;
3786
3787         if (compose_check_entries(compose, TRUE) == FALSE)
3788                 goto bail;
3789
3790         val = compose_queue(compose, &msgnum, &folder, &msgpath);
3791
3792         if (val) {
3793                 if (val == -4) {
3794                         alertpanel_error(_("Could not queue message for sending:\n\n"
3795                                            "Charset conversion failed."));
3796                 } else if (val == -3) {
3797                         alertpanel_error(_("Could not queue message for sending:\n\n"
3798                                            "Signature failed."));
3799                 } else if (val == -2 && errno != 0) {
3800                         alertpanel_error(_("Could not queue message for sending:\n\n%s."), strerror(errno));
3801                 } else {
3802                         alertpanel_error(_("Could not queue message for sending."));
3803                 }
3804                 goto bail;
3805         }
3806
3807
3808         if (prefs_common.send_dialog_mode != SEND_DIALOG_ALWAYS) {
3809                 compose->sending = FALSE;
3810                 compose_close(compose);
3811                 /* No more compose access in the normal codepath 
3812                  * after this point! */
3813                 compose = NULL;
3814         }
3815
3816         if (msgnum == 0) {
3817                 alertpanel_error(_("The message was queued but could not be "
3818                                    "sent.\nUse \"Send queued messages\" from "
3819                                    "the main window to retry."));
3820                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3821                         compose->sending = FALSE;
3822                         compose->modified = TRUE; 
3823                         compose_allow_user_actions (compose, TRUE);
3824                 }
3825                 return 0;
3826         }
3827         
3828         if (msgpath == NULL) {
3829                 msgpath = folder_item_fetch_msg(folder, msgnum);
3830                 val = procmsg_send_message_queue(msgpath);
3831                 g_free(msgpath);
3832         } else {
3833                 val = procmsg_send_message_queue(msgpath);
3834                 g_unlink(msgpath);
3835                 g_free(msgpath);
3836         }
3837         if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3838                 compose->sending = FALSE;
3839                 compose_allow_user_actions (compose, TRUE);
3840                 if (val != 0) {
3841                         folder_item_remove_msg(folder, msgnum);
3842                         folder_item_scan(folder);
3843                 }
3844         }
3845
3846         if (val == 0) {
3847                 folder_item_remove_msg(folder, msgnum);
3848                 folder_item_scan(folder);
3849                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS)
3850                         compose_close(compose);
3851         } else {
3852                 alertpanel_error(_("The message was queued but could not be "
3853                                    "sent.\nUse \"Send queued messages\" from "
3854                                    "the main window to retry."));
3855                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3856                         compose_allow_user_actions (compose, TRUE);
3857                         compose->modified = TRUE; 
3858                         compose->sending = FALSE;               
3859                 }
3860                 return -1;
3861         }
3862
3863         return 0;
3864
3865 bail:
3866         compose_allow_user_actions (compose, TRUE);
3867         compose->sending = FALSE;
3868         compose->modified = TRUE; 
3869
3870         return -1;
3871 }
3872
3873 static gboolean compose_use_attach(Compose *compose) 
3874 {
3875         GtkTreeModel *model = gtk_tree_view_get_model
3876                                 (GTK_TREE_VIEW(compose->attach_clist));
3877         return gtk_tree_model_iter_n_children(model, NULL) > 0;
3878 }
3879
3880 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3881                                                            FILE *fp)
3882 {
3883         gchar buf[BUFFSIZE];
3884         gchar *str;
3885         gboolean first_to_address;
3886         gboolean first_cc_address;
3887         GSList *list;
3888         ComposeHeaderEntry *headerentry;
3889         const gchar *headerentryname;
3890         gchar *cc_hdr;
3891         gchar *to_hdr;
3892
3893         debug_print("Writing redirect header\n");
3894
3895         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3896         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3897
3898         first_to_address = TRUE;
3899         for (list = compose->header_list; list; list = list->next) {
3900                 headerentry = ((ComposeHeaderEntry *)list->data);
3901                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3902
3903                 if (g_utf8_collate(headerentryname, to_hdr) == 0) {
3904                         const gchar *entstr = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3905                         Xstrdup_a(str, entstr, return -1);
3906                         g_strstrip(str);
3907                         if (str[0] != '\0') {
3908                                 compose_convert_header
3909                                         (compose, buf, sizeof(buf), str,
3910                                         strlen("Resent-To") + 2, TRUE);
3911
3912                                 if (first_to_address) {
3913                                         fprintf(fp, "Resent-To: ");
3914                                         first_to_address = FALSE;
3915                                 } else {
3916                                         fprintf(fp, ",");
3917                                 }
3918                                 fprintf(fp, "%s", buf);
3919                         }
3920                 }
3921         }
3922         if (!first_to_address) {
3923                 fprintf(fp, "\n");
3924         }
3925
3926         first_cc_address = TRUE;
3927         for (list = compose->header_list; list; list = list->next) {
3928                 headerentry = ((ComposeHeaderEntry *)list->data);
3929                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3930
3931                 if (g_utf8_collate(headerentryname, cc_hdr) == 0) {
3932                         const gchar *strg = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3933                         Xstrdup_a(str, strg, return -1);
3934                         g_strstrip(str);
3935                         if (str[0] != '\0') {
3936                                 compose_convert_header
3937                                         (compose, buf, sizeof(buf), str,
3938                                         strlen("Resent-Cc") + 2, TRUE);
3939
3940                                 if (first_cc_address) {
3941                                         fprintf(fp, "Resent-Cc: ");
3942                                         first_cc_address = FALSE;
3943                                 } else {
3944                                         fprintf(fp, ",");
3945                                 }
3946                                 fprintf(fp, "%s", buf);
3947                         }
3948                 }
3949         }
3950         if (!first_cc_address) {
3951                 fprintf(fp, "\n");
3952         }
3953         
3954         return(0);
3955 }
3956
3957 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3958 {
3959         gchar buf[BUFFSIZE];
3960         gchar *str;
3961         const gchar *entstr;
3962         /* struct utsname utsbuf; */
3963
3964         g_return_val_if_fail(fp != NULL, -1);
3965         g_return_val_if_fail(compose->account != NULL, -1);
3966         g_return_val_if_fail(compose->account->address != NULL, -1);
3967
3968         /* Resent-Date */
3969         get_rfc822_date(buf, sizeof(buf));
3970         fprintf(fp, "Resent-Date: %s\n", buf);
3971
3972         /* Resent-From */
3973         if (compose->account->name && *compose->account->name) {
3974                 compose_convert_header
3975                         (compose, buf, sizeof(buf), compose->account->name,
3976                          strlen("From: "), TRUE);
3977                 fprintf(fp, "Resent-From: %s <%s>\n",
3978                         buf, compose->account->address);
3979         } else
3980                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3981
3982         /* Subject */
3983         entstr = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3984         if (*entstr != '\0') {
3985                 Xstrdup_a(str, entstr, return -1);
3986                 g_strstrip(str);
3987                 if (*str != '\0') {
3988                         compose_convert_header(compose, buf, sizeof(buf), str,
3989                                                strlen("Subject: "), FALSE);
3990                         fprintf(fp, "Subject: %s\n", buf);
3991                 }
3992         }
3993
3994         /* Resent-Message-ID */
3995         if (compose->account->gen_msgid) {
3996                 generate_msgid(buf, sizeof(buf));
3997                 fprintf(fp, "Resent-Message-ID: <%s>\n", buf);
3998                 compose->msgid = g_strdup(buf);
3999         }
4000
4001         compose_redirect_write_headers_from_headerlist(compose, fp);
4002
4003         /* separator between header and body */
4004         fputs("\n", fp);
4005
4006         return 0;
4007 }
4008
4009 static gint compose_redirect_write_to_file(Compose *compose, FILE *fdest)
4010 {
4011         FILE *fp;
4012         size_t len;
4013         gchar buf[BUFFSIZE];
4014
4015         if ((fp = g_fopen(compose->redirect_filename, "rb")) == NULL) {
4016                 FILE_OP_ERROR(compose->redirect_filename, "fopen");
4017                 return -1;
4018         }
4019
4020         while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
4021                 /* should filter returnpath, delivered-to */
4022                 if (g_ascii_strncasecmp(buf, "Return-Path:",
4023                                         strlen("Return-Path:")) == 0 ||
4024                     g_ascii_strncasecmp(buf, "Delivered-To:",
4025                                         strlen("Delivered-To:")) == 0 ||
4026                     g_ascii_strncasecmp(buf, "Received:",
4027                                         strlen("Received:")) == 0 ||
4028                     g_ascii_strncasecmp(buf, "Subject:",
4029                                         strlen("Subject:")) == 0 ||
4030                     g_ascii_strncasecmp(buf, "X-UIDL:",
4031                                         strlen("X-UIDL:")) == 0)
4032                         continue;
4033
4034                 if (fputs(buf, fdest) == -1)
4035                         goto error;
4036
4037                 if (!prefs_common.redirect_keep_from) {
4038                         if (g_ascii_strncasecmp(buf, "From:",
4039                                           strlen("From:")) == 0) {
4040                                 fputs(" (by way of ", fdest);
4041                                 if (compose->account->name
4042                                     && *compose->account->name) {
4043                                         compose_convert_header
4044                                                 (compose, buf, sizeof(buf),
4045                                                  compose->account->name,
4046                                                  strlen("From: "),
4047                                                  FALSE);
4048                                         fprintf(fdest, "%s <%s>",
4049                                                 buf,
4050                                                 compose->account->address);
4051                                 } else
4052                                         fprintf(fdest, "%s",
4053                                                 compose->account->address);
4054                                 fputs(")", fdest);
4055                         }
4056                 }
4057
4058                 if (fputs("\n", fdest) == -1)
4059                         goto error;
4060         }
4061
4062         compose_redirect_write_headers(compose, fdest);
4063
4064         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
4065                 if (fwrite(buf, sizeof(gchar), len, fdest) != len)
4066                         goto error;
4067         }
4068
4069         fclose(fp);
4070
4071         return 0;
4072 error:
4073         fclose(fp);
4074
4075         return -1;
4076 }
4077
4078 static gint compose_write_to_file(Compose *compose, FILE *fp, gint action)
4079 {
4080         GtkTextBuffer *buffer;
4081         GtkTextIter start, end;
4082         gchar *chars;
4083         gchar *buf;
4084         const gchar *out_codeset;
4085         EncodingType encoding;
4086         MimeInfo *mimemsg, *mimetext;
4087         gint line;
4088
4089         /* create message MimeInfo */
4090         mimemsg = procmime_mimeinfo_new();
4091         mimemsg->type = MIMETYPE_MESSAGE;
4092         mimemsg->subtype = g_strdup("rfc822");
4093         mimemsg->content = MIMECONTENT_MEM;
4094         mimemsg->tmp = TRUE; /* must free content later */
4095         mimemsg->data.mem = compose_get_header(compose);
4096
4097         /* Create text part MimeInfo */
4098         /* get all composed text */
4099         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
4100         gtk_text_buffer_get_start_iter(buffer, &start);
4101         gtk_text_buffer_get_end_iter(buffer, &end);
4102         chars = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
4103         if (is_ascii_str(chars)) {
4104                 buf = chars;
4105                 chars = NULL;
4106                 out_codeset = CS_US_ASCII;
4107                 encoding = ENC_7BIT;
4108         } else {
4109                 const gchar *src_codeset = CS_INTERNAL;
4110
4111                 out_codeset = conv_get_charset_str(compose->out_encoding);
4112
4113                 if (!out_codeset) {
4114                         gchar *test_conv_global_out = NULL;
4115                         gchar *test_conv_reply = NULL;
4116
4117                         /* automatic mode. be automatic. */
4118                         codeconv_set_strict(TRUE);
4119                         
4120                         out_codeset = conv_get_outgoing_charset_str();
4121                         if (out_codeset) {
4122                                 debug_print("trying to convert to %s\n", out_codeset);
4123                                 test_conv_global_out = conv_codeset_strdup(chars, src_codeset, out_codeset);
4124                         }
4125                         
4126                         if (!test_conv_global_out && compose->orig_charset
4127                         &&  strcmp(compose->orig_charset, CS_US_ASCII)) {
4128                                 out_codeset = compose->orig_charset;
4129                                 debug_print("failure; trying to convert to %s\n", out_codeset);
4130                                 test_conv_reply = conv_codeset_strdup(chars, src_codeset, out_codeset);
4131                         }
4132                         
4133                         if (!test_conv_global_out && !test_conv_reply) {
4134                                 /* we're lost */
4135                                 out_codeset = CS_INTERNAL;
4136                                 debug_print("failure; finally using %s\n", out_codeset);
4137                         }
4138                         g_free(test_conv_global_out);
4139                         g_free(test_conv_reply);
4140                         codeconv_set_strict(FALSE);
4141                 }
4142
4143                 if (!g_ascii_strcasecmp(out_codeset, CS_US_ASCII))
4144                         out_codeset = CS_ISO_8859_1;
4145
4146                 if (prefs_common.encoding_method == CTE_BASE64)
4147                         encoding = ENC_BASE64;
4148                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
4149                         encoding = ENC_QUOTED_PRINTABLE;
4150                 else if (prefs_common.encoding_method == CTE_8BIT)
4151                         encoding = ENC_8BIT;
4152                 else
4153                         encoding = procmime_get_encoding_for_charset(out_codeset);
4154
4155                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
4156                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
4157
4158                 if (action == COMPOSE_WRITE_FOR_SEND) {
4159                         codeconv_set_strict(TRUE);
4160                         buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
4161                         codeconv_set_strict(FALSE);
4162
4163                         if (!buf) {
4164                                 AlertValue aval;
4165                                 gchar *msg;
4166
4167                                 msg = g_strdup_printf(_("Can't convert the character encoding of the message \n"
4168                                                         "to the specified %s charset.\n"
4169                                                         "Send it as %s?"), out_codeset, src_codeset);
4170                                 aval = alertpanel_full(_("Error"), msg, GTK_STOCK_CANCEL, _("+_Send"), NULL, FALSE,
4171                                                       NULL, ALERT_ERROR, G_ALERTDEFAULT);
4172                                 g_free(msg);
4173
4174                                 if (aval != G_ALERTALTERNATE) {
4175                                         g_free(chars);
4176                                         return -3;
4177                                 } else {
4178                                         buf = chars;
4179                                         out_codeset = src_codeset;
4180                                         chars = NULL;
4181                                 }
4182                         }
4183                 } else {
4184                         buf = chars;
4185                         out_codeset = src_codeset;
4186                         chars = NULL;
4187                 }
4188         }
4189         g_free(chars);
4190
4191         if (encoding == ENC_8BIT || encoding == ENC_7BIT) {
4192                 if (!strncmp(buf, "From ", sizeof("From ")-1) ||
4193                     strstr(buf, "\nFrom ") != NULL) {
4194                         encoding = ENC_QUOTED_PRINTABLE;
4195                 }
4196         }
4197
4198         mimetext = procmime_mimeinfo_new();
4199         mimetext->content = MIMECONTENT_MEM;
4200         mimetext->tmp = TRUE; /* must free content later */
4201         mimetext->data.mem = buf;
4202         mimetext->type = MIMETYPE_TEXT;
4203         mimetext->subtype = g_strdup("plain");
4204         g_hash_table_insert(mimetext->typeparameters, g_strdup("charset"),
4205                             g_strdup(out_codeset));
4206         /* protect trailing spaces when signing message */
4207         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
4208             privacy_system_can_sign(compose->privacy_system)) {
4209                 encoding = ENC_QUOTED_PRINTABLE;
4210         }
4211         
4212         /* check for line length limit */
4213         if (action == COMPOSE_WRITE_FOR_SEND &&
4214             encoding != ENC_QUOTED_PRINTABLE && encoding != ENC_BASE64 &&
4215             check_line_length(buf, 1000, &line) < 0) {
4216                 AlertValue aval;
4217                 gchar *msg;
4218
4219                 msg = g_strdup_printf
4220                         (_("Line %d exceeds the line length limit (998 bytes).\n"
4221                            "The contents of the message might be broken on the way to the delivery.\n"
4222                            "\n"
4223                            "Send it anyway?"), line + 1);
4224                 aval = alertpanel(_("Warning"), msg, GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL);
4225                 g_free(msg);
4226                 if (aval != G_ALERTALTERNATE) {
4227                         return -1;
4228                 }
4229         }
4230         
4231         if (encoding != ENC_UNKNOWN)
4232                 procmime_encode_content(mimetext, encoding);
4233
4234         /* append attachment parts */
4235         if (compose_use_attach(compose)) {
4236                 MimeInfo *mimempart;
4237                 gchar *boundary = NULL;
4238                 mimempart = procmime_mimeinfo_new();
4239                 mimempart->content = MIMECONTENT_EMPTY;
4240                 mimempart->type = MIMETYPE_MULTIPART;
4241                 mimempart->subtype = g_strdup("mixed");
4242
4243                 do {
4244                         if (boundary)
4245                                 g_free(boundary);
4246                         boundary = generate_mime_boundary(NULL);
4247                 } while (strstr(buf, boundary) != NULL);
4248
4249                 g_hash_table_insert(mimempart->typeparameters, g_strdup("boundary"),
4250                                     boundary);
4251
4252                 mimetext->disposition = DISPOSITIONTYPE_INLINE;
4253
4254                 g_node_append(mimempart->node, mimetext->node);
4255                 g_node_append(mimemsg->node, mimempart->node);
4256
4257                 compose_add_attachments(compose, mimempart);
4258         } else
4259                 g_node_append(mimemsg->node, mimetext->node);
4260
4261         /* sign message if sending */
4262         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
4263             privacy_system_can_sign(compose->privacy_system))
4264                 if (!privacy_sign(compose->privacy_system, mimemsg, compose->account))
4265                         return -2;
4266
4267         procmime_write_mimeinfo(mimemsg, fp);
4268         
4269         procmime_mimeinfo_free_all(mimemsg);
4270
4271         return 0;
4272 }
4273
4274 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
4275 {
4276         GtkTextBuffer *buffer;
4277         GtkTextIter start, end;
4278         FILE *fp;
4279         size_t len;
4280         gchar *chars, *tmp;
4281
4282         if ((fp = g_fopen(file, "wb")) == NULL) {
4283                 FILE_OP_ERROR(file, "fopen");
4284                 return -1;
4285         }
4286
4287         /* chmod for security */
4288         if (change_file_mode_rw(fp, file) < 0) {
4289                 FILE_OP_ERROR(file, "chmod");
4290                 g_warning("can't change file mode\n");
4291         }
4292
4293         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
4294         gtk_text_buffer_get_start_iter(buffer, &start);
4295         gtk_text_buffer_get_end_iter(buffer, &end);
4296         tmp = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
4297
4298         chars = conv_codeset_strdup
4299                 (tmp, CS_INTERNAL, conv_get_locale_charset_str());
4300
4301         g_free(tmp);
4302         if (!chars) return -1;
4303
4304         /* write body */
4305         len = strlen(chars);
4306         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
4307                 FILE_OP_ERROR(file, "fwrite");
4308                 g_free(chars);
4309                 fclose(fp);
4310                 g_unlink(file);
4311                 return -1;
4312         }
4313
4314         g_free(chars);
4315
4316         if (fclose(fp) == EOF) {
4317                 FILE_OP_ERROR(file, "fclose");
4318                 g_unlink(file);
4319                 return -1;
4320         }
4321         return 0;
4322 }
4323
4324 static gint compose_remove_reedit_target(Compose *compose, gboolean force)
4325 {
4326         FolderItem *item;
4327         MsgInfo *msginfo = compose->targetinfo;
4328
4329         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
4330         if (!msginfo) return -1;
4331
4332         if (!force && MSG_IS_LOCKED(msginfo->flags))
4333                 return 0;
4334
4335         item = msginfo->folder;
4336         g_return_val_if_fail(item != NULL, -1);
4337
4338         if (procmsg_msg_exist(msginfo) &&
4339             (folder_has_parent_of_type(item, F_QUEUE) ||
4340              folder_has_parent_of_type(item, F_DRAFT) 
4341              || msginfo == compose->autosaved_draft)) {
4342                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
4343                         g_warning("can't remove the old message\n");
4344                         return -1;
4345                 }
4346         }
4347
4348         return 0;
4349 }
4350
4351 void compose_remove_draft(Compose *compose)
4352 {
4353         FolderItem *drafts;
4354         MsgInfo *msginfo = compose->targetinfo;
4355         drafts = account_get_special_folder(compose->account, F_DRAFT);
4356
4357         if (procmsg_msg_exist(msginfo)) {
4358                 folder_item_remove_msg(drafts, msginfo->msgnum);
4359         }
4360
4361 }
4362
4363 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item, gchar **msgpath)
4364 {
4365         return compose_queue_sub (compose, msgnum, item, msgpath, FALSE);
4366 }
4367 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gchar **msgpath, gboolean check_subject)
4368 {
4369         FolderItem *queue;
4370         gchar *tmp;
4371         FILE *fp;
4372         GSList *cur;
4373         gint num;
4374         static gboolean lock = FALSE;
4375         PrefsAccount *mailac = NULL, *newsac = NULL;
4376         
4377         debug_print("queueing message...\n");
4378         g_return_val_if_fail(compose->account != NULL, -1);
4379
4380         lock = TRUE;
4381         
4382         if (compose_check_entries(compose, check_subject) == FALSE) {
4383                 lock = FALSE;
4384                 return -1;
4385         }
4386
4387         if (!compose->to_list && !compose->newsgroup_list) {
4388                 g_warning("can't get recipient list.");
4389                 lock = FALSE;
4390                 return -1;
4391         }
4392
4393         if (compose->to_list) {
4394                 if (compose->account->protocol != A_NNTP)
4395                         mailac = compose->account;
4396                 else if (cur_account && cur_account->protocol != A_NNTP)
4397                         mailac = cur_account;
4398                 else if (!(mailac = compose_current_mail_account())) {
4399                         lock = FALSE;
4400                         alertpanel_error(_("No account for sending mails available!"));
4401                         return -1;
4402                 }
4403         }
4404
4405         if (compose->newsgroup_list) {
4406                 if (compose->account->protocol == A_NNTP)
4407                         newsac = compose->account;
4408                 else if (!newsac->protocol != A_NNTP) {
4409                         lock = FALSE;
4410                         alertpanel_error(_("No account for posting news available!"));
4411                         return -1;
4412                 }                       
4413         }
4414
4415         /* write queue header */
4416         tmp = g_strdup_printf("%s%cqueue.%p", get_tmp_dir(),
4417                               G_DIR_SEPARATOR, compose);
4418         if ((fp = g_fopen(tmp, "wb")) == NULL) {
4419                 FILE_OP_ERROR(tmp, "fopen");
4420                 g_free(tmp);
4421                 return -2;
4422         }
4423
4424         if (change_file_mode_rw(fp, tmp) < 0) {
4425                 FILE_OP_ERROR(tmp, "chmod");
4426                 g_warning("can't change file mode\n");
4427         }
4428
4429         /* queueing variables */
4430         fprintf(fp, "AF:\n");
4431         fprintf(fp, "NF:0\n");
4432         fprintf(fp, "PS:10\n");
4433         fprintf(fp, "SRH:1\n");
4434         fprintf(fp, "SFN:\n");
4435         fprintf(fp, "DSR:\n");
4436         if (compose->msgid)
4437                 fprintf(fp, "MID:<%s>\n", compose->msgid);
4438         else
4439                 fprintf(fp, "MID:\n");
4440         fprintf(fp, "CFG:\n");
4441         fprintf(fp, "PT:0\n");
4442         fprintf(fp, "S:%s\n", compose->account->address);
4443         fprintf(fp, "RQ:\n");
4444         if (mailac)
4445                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
4446         else
4447                 fprintf(fp, "SSV:\n");
4448         if (newsac)
4449                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
4450         else
4451                 fprintf(fp, "NSV:\n");
4452         fprintf(fp, "SSH:\n");
4453         /* write recepient list */
4454         if (compose->to_list) {
4455                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
4456                 for (cur = compose->to_list->next; cur != NULL;
4457                      cur = cur->next)
4458                         fprintf(fp, ",<%s>", (gchar *)cur->data);
4459                 fprintf(fp, "\n");
4460         }
4461         /* write newsgroup list */
4462         if (compose->newsgroup_list) {
4463                 fprintf(fp, "NG:");
4464                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
4465                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
4466                         fprintf(fp, ",%s", (gchar *)cur->data);
4467                 fprintf(fp, "\n");
4468         }
4469         /* Sylpheed account IDs */
4470         if (mailac)
4471                 fprintf(fp, "MAID:%d\n", mailac->account_id);
4472         if (newsac)
4473                 fprintf(fp, "NAID:%d\n", newsac->account_id);
4474
4475         if (compose->privacy_system != NULL) {
4476                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
4477                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
4478                 if (compose->use_encryption) {
4479                         gchar *encdata;
4480
4481                         encdata = privacy_get_encrypt_data(compose->privacy_system, compose->to_list);
4482                         if (encdata != NULL) {
4483                                 if (strcmp(encdata, "_DONT_ENCRYPT_")) {
4484                                         fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
4485                                         fprintf(fp, "X-Sylpheed-Encrypt-Data:%s\n", 
4486                                                 encdata);
4487                                 } /* else we finally dont want to encrypt */
4488                         } else {
4489                                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
4490                                 /* and if encdata was null, it means there's been a problem in 
4491                                  * key selection */
4492                         }
4493                         g_free(encdata);
4494                 }
4495         }
4496
4497         /* Save copy folder */
4498         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
4499                 gchar *savefolderid;
4500                 
4501                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
4502                 fprintf(fp, "SCF:%s\n", savefolderid);
4503                 g_free(savefolderid);
4504         }
4505         /* Save copy folder */
4506         if (compose->return_receipt) {
4507                 fprintf(fp, "RRCPT:1\n");
4508         }
4509         /* Message-ID of message replying to */
4510         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
4511                 gchar *folderid;
4512                 
4513                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
4514                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
4515                 g_free(folderid);
4516         }
4517         /* Message-ID of message forwarding to */
4518         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
4519                 gchar *folderid;
4520                 
4521                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
4522                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
4523                 g_free(folderid);
4524         }
4525         fprintf(fp, "\n");
4526
4527         if (compose->redirect_filename != NULL) {
4528                 if (compose_redirect_write_to_file(compose, fp) < 0) {
4529                         lock = FALSE;
4530                         fclose(fp);
4531                         g_unlink(tmp);
4532                         g_free(tmp);
4533                         return -2;
4534                 }
4535         } else {
4536                 gint result = 0;
4537                 if ((result = compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_SEND)) < 0) {
4538                         lock = FALSE;
4539                         fclose(fp);
4540                         g_unlink(tmp);
4541                         g_free(tmp);
4542                         return result - 1; /* -2 for a generic error, -3 for signing error, -4 for encoding */
4543                 }
4544         }
4545
4546         if (fclose(fp) == EOF) {
4547                 FILE_OP_ERROR(tmp, "fclose");
4548                 g_unlink(tmp);
4549                 g_free(tmp);
4550                 return -2;
4551         }
4552
4553         queue = account_get_special_folder(compose->account, F_QUEUE);
4554         if (!queue) {
4555                 g_warning("can't find queue folder\n");
4556                 g_unlink(tmp);
4557                 g_free(tmp);
4558                 return -1;
4559         }
4560         folder_item_scan(queue);
4561         if ((num = folder_item_add_msg(queue, tmp, NULL, FALSE)) < 0) {
4562                 g_warning("can't queue the message\n");
4563                 g_unlink(tmp);
4564                 g_free(tmp);
4565                 return -1;
4566         }
4567         
4568         if (msgpath == NULL) {
4569                 g_unlink(tmp);
4570                 g_free(tmp);
4571         } else
4572                 *msgpath = tmp;
4573
4574         if (compose->mode == COMPOSE_REEDIT) {
4575                 compose_remove_reedit_target(compose, FALSE);
4576         }
4577
4578         if ((msgnum != NULL) && (item != NULL)) {
4579                 *msgnum = num;
4580                 *item = queue;
4581         }
4582
4583         return 0;
4584 }
4585
4586 static void compose_add_attachments(Compose *compose, MimeInfo *parent)
4587 {
4588         AttachInfo *ainfo;
4589         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
4590         MimeInfo *mimepart;
4591         struct stat statbuf;
4592         gchar *type, *subtype;
4593         GtkTreeModel *model;
4594         GtkTreeIter iter;
4595
4596         model = gtk_tree_view_get_model(tree_view);
4597         
4598         if (!gtk_tree_model_get_iter_first(model, &iter))
4599                 return;
4600         do {
4601                 gtk_tree_model_get(model, &iter,
4602                                    COL_DATA, &ainfo,
4603                                    -1);
4604                                                            
4605                 mimepart = procmime_mimeinfo_new();
4606                 mimepart->content = MIMECONTENT_FILE;
4607                 mimepart->data.filename = g_strdup(ainfo->file);
4608                 mimepart->tmp = FALSE; /* or we destroy our attachment */
4609                 mimepart->offset = 0;
4610
4611                 stat(ainfo->file, &statbuf);
4612                 mimepart->length = statbuf.st_size;
4613
4614                 type = g_strdup(ainfo->content_type);
4615
4616                 if (!strchr(type, '/')) {
4617                         g_free(type);
4618                         type = g_strdup("application/octet-stream");
4619                 }
4620
4621                 subtype = strchr(type, '/') + 1;
4622                 *(subtype - 1) = '\0';
4623                 mimepart->type = procmime_get_media_type(type);
4624                 mimepart->subtype = g_strdup(subtype);
4625                 g_free(type);
4626
4627                 if (mimepart->type == MIMETYPE_MESSAGE && 
4628                     !g_ascii_strcasecmp(mimepart->subtype, "rfc822")) {
4629                         mimepart->disposition = DISPOSITIONTYPE_INLINE;
4630                 } else {
4631                         g_hash_table_insert(mimepart->typeparameters,
4632                                             g_strdup("name"), g_strdup(ainfo->name));
4633                         g_hash_table_insert(mimepart->dispositionparameters,
4634                                             g_strdup("filename"), g_strdup(ainfo->name));
4635                         mimepart->disposition = DISPOSITIONTYPE_ATTACHMENT;
4636                 }
4637
4638                 if (compose->use_signing) {
4639                         if (ainfo->encoding == ENC_7BIT)
4640                                 ainfo->encoding = ENC_QUOTED_PRINTABLE;
4641                         else if (ainfo->encoding == ENC_8BIT)
4642                                 ainfo->encoding = ENC_BASE64;
4643                 }
4644                 
4645                 procmime_encode_content(mimepart, ainfo->encoding);
4646
4647                 g_node_append(parent->node, mimepart->node);
4648         } while (gtk_tree_model_iter_next(model, &iter));
4649 }
4650
4651 #define QUOTE_IF_REQUIRED(out, str)                                     \
4652 {                                                                       \
4653         if (*str != '"' && strpbrk(str, ",.[]<>")) {                    \
4654                 gchar *__tmp;                                           \
4655                 gint len;                                               \
4656                                                                         \
4657                 len = strlen(str) + 3;                                  \
4658                 if ((__tmp = alloca(len)) == NULL) {                    \
4659                         g_warning("can't allocate memory\n");           \
4660                         g_string_free(header, TRUE);                    \
4661                         return NULL;                                    \
4662                 }                                                       \
4663                 g_snprintf(__tmp, len, "\"%s\"", str);                  \
4664                 out = __tmp;                                            \
4665         } else {                                                        \
4666                 gchar *__tmp;                                           \
4667                                                                         \
4668                 if ((__tmp = alloca(strlen(str) + 1)) == NULL) {        \
4669                         g_warning("can't allocate memory\n");           \
4670                         g_string_free(header, TRUE);                    \
4671                         return NULL;                                    \
4672                 } else                                                  \
4673                         strcpy(__tmp, str);                             \
4674                                                                         \
4675                 out = __tmp;                                            \
4676         }                                                               \
4677 }
4678
4679 #define IS_IN_CUSTOM_HEADER(header) \
4680         (compose->account->add_customhdr && \
4681          custom_header_find(compose->account->customhdr_list, header) != NULL)
4682
4683 static void compose_add_headerfield_from_headerlist(Compose *compose, 
4684                                                     GString *header, 
4685                                                     const gchar *fieldname,
4686                                                     const gchar *seperator)
4687 {
4688         gchar *str, *fieldname_w_colon, *trans_fieldname;
4689         gboolean add_field = FALSE;
4690         GSList *list;
4691         ComposeHeaderEntry *headerentry;
4692         const gchar * headerentryname;
4693         GString *fieldstr;
4694
4695         if (IS_IN_CUSTOM_HEADER(fieldname))
4696                 return;
4697
4698         debug_print("Adding %s-fields\n", fieldname);
4699
4700         fieldstr = g_string_sized_new(64);
4701
4702         fieldname_w_colon = g_strconcat(fieldname, ":", NULL);
4703         trans_fieldname = (prefs_common.trans_hdr ? gettext(fieldname_w_colon) : fieldname_w_colon);
4704
4705         for (list = compose->header_list; list; list = list->next) {
4706                 headerentry = ((ComposeHeaderEntry *)list->data);
4707                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
4708
4709                 if (!g_utf8_collate(trans_fieldname, headerentryname)) {
4710                         str = gtk_editable_get_chars(GTK_EDITABLE(headerentry->entry), 0, -1);
4711                         g_strstrip(str);
4712                         if (str[0] != '\0') {
4713                                 if (add_field)
4714                                         g_string_append(fieldstr, seperator);
4715                                 g_string_append(fieldstr, str);
4716                                 add_field = TRUE;
4717                         }
4718                         g_free(str);
4719                 }
4720         }
4721         if (add_field) {
4722                 gchar *buf;
4723
4724                 buf = g_new0(gchar, fieldstr->len * 4 + 256);
4725                 compose_convert_header
4726                         (compose, buf, fieldstr->len * 4  + 256, fieldstr->str,
4727                         strlen(fieldname) + 2, TRUE);
4728                 g_string_append_printf(header, "%s: %s\n", fieldname, buf);
4729                 g_free(buf);
4730         }
4731
4732         g_free(fieldname_w_colon);
4733         g_string_free(fieldstr, TRUE);
4734
4735         return;
4736 }
4737
4738 static gchar *compose_get_header(Compose *compose)
4739 {
4740         gchar buf[BUFFSIZE];
4741         const gchar *entry_str;
4742         gchar *str;
4743         gchar *name;
4744         GSList *list;
4745         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4746         GString *header;
4747
4748         g_return_val_if_fail(compose->account != NULL, NULL);
4749         g_return_val_if_fail(compose->account->address != NULL, NULL);
4750
4751         header = g_string_sized_new(64);
4752
4753         /* Date */
4754         if (compose->account->add_date) {
4755                 get_rfc822_date(buf, sizeof(buf));
4756                 g_string_append_printf(header, "Date: %s\n", buf);
4757         }
4758
4759         /* From */
4760         if (compose->account->name && *compose->account->name) {
4761                 compose_convert_header
4762                         (compose, buf, sizeof(buf), compose->account->name,
4763                          strlen("From: "), TRUE);
4764                 QUOTE_IF_REQUIRED(name, buf);
4765                 g_string_append_printf(header, "From: %s <%s>\n",
4766                         name, compose->account->address);
4767         } else
4768                 g_string_append_printf(header, "From: %s\n", compose->account->address);
4769         
4770         /* To */
4771         compose_add_headerfield_from_headerlist(compose, header, "To", ", ");
4772
4773         /* Newsgroups */
4774         compose_add_headerfield_from_headerlist(compose, header, "Newsgroups", ",");
4775
4776         /* Cc */
4777         compose_add_headerfield_from_headerlist(compose, header, "Cc", ", ");
4778
4779         /* Bcc */
4780         compose_add_headerfield_from_headerlist(compose, header, "Bcc", ", ");
4781
4782         /* Subject */
4783         str = gtk_editable_get_chars(GTK_EDITABLE(compose->subject_entry), 0, -1);
4784
4785         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
4786                 g_strstrip(str);
4787                 if (*str != '\0') {
4788                         compose_convert_header(compose, buf, sizeof(buf), str,
4789                                                strlen("Subject: "), FALSE);
4790                         g_string_append_printf(header, "Subject: %s\n", buf);
4791                 }
4792         }
4793         g_free(str);
4794
4795         /* Message-ID */
4796         if (compose->account->gen_msgid) {
4797                 generate_msgid(buf, sizeof(buf));
4798                 g_string_append_printf(header, "Message-ID: <%s>\n", buf);
4799                 compose->msgid = g_strdup(buf);
4800         }
4801
4802         if (compose->remove_references == FALSE) {
4803                 /* In-Reply-To */
4804                 if (compose->inreplyto && compose->to_list)
4805                         g_string_append_printf(header, "In-Reply-To: <%s>\n", compose->inreplyto);
4806         
4807                 /* References */
4808                 if (compose->references)
4809                         g_string_append_printf(header, "References: %s\n", compose->references);
4810         }
4811
4812         /* Followup-To */
4813         compose_add_headerfield_from_headerlist(compose, header, "Followup-To", ",");
4814
4815         /* Reply-To */
4816         compose_add_headerfield_from_headerlist(compose, header, "Reply-To", ", ");
4817
4818         /* Organization */
4819         if (compose->account->organization &&
4820             strlen(compose->account->organization) &&
4821             !IS_IN_CUSTOM_HEADER("Organization")) {
4822                 compose_convert_header(compose, buf, sizeof(buf),
4823                                        compose->account->organization,
4824                                        strlen("Organization: "), FALSE);
4825                 g_string_append_printf(header, "Organization: %s\n", buf);
4826         }
4827
4828         /* Program version and system info */
4829         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer") &&
4830             !compose->newsgroup_list) {
4831                 g_string_append_printf(header, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
4832                         prog_version,
4833                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4834                         TARGET_ALIAS);
4835         }
4836         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4837                 g_string_append_printf(header, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4838                         prog_version,
4839                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4840                         TARGET_ALIAS);
4841         }
4842
4843         /* custom headers */
4844         if (compose->account->add_customhdr) {
4845                 GSList *cur;
4846
4847                 for (cur = compose->account->customhdr_list; cur != NULL;
4848                      cur = cur->next) {
4849                         CustomHeader *chdr = (CustomHeader *)cur->data;
4850
4851                         if (custom_header_is_allowed(chdr->name)) {
4852                                 compose_convert_header
4853                                         (compose, buf, sizeof(buf),
4854                                          chdr->value ? chdr->value : "",
4855                                          strlen(chdr->name) + 2, FALSE);
4856                                 g_string_append_printf(header, "%s: %s\n", chdr->name, buf);
4857                         }
4858                 }
4859         }
4860
4861         /* PRIORITY */
4862         switch (compose->priority) {
4863                 case PRIORITY_HIGHEST: g_string_append_printf(header, "Importance: high\n"
4864                                                    "X-Priority: 1 (Highest)\n");
4865                         break;
4866                 case PRIORITY_HIGH: g_string_append_printf(header, "Importance: high\n"
4867                                                 "X-Priority: 2 (High)\n");
4868                         break;
4869                 case PRIORITY_NORMAL: break;
4870                 case PRIORITY_LOW: g_string_append_printf(header, "Importance: low\n"
4871                                                "X-Priority: 4 (Low)\n");
4872                         break;
4873                 case PRIORITY_LOWEST: g_string_append_printf(header, "Importance: low\n"
4874                                                   "X-Priority: 5 (Lowest)\n");
4875                         break;
4876                 default: debug_print("compose: priority unknown : %d\n",
4877                                      compose->priority);
4878         }
4879
4880         /* Request Return Receipt */
4881         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4882                 if (compose->return_receipt) {
4883                         if (compose->account->name
4884                             && *compose->account->name) {
4885                                 compose_convert_header(compose, buf, sizeof(buf), 
4886                                                        compose->account->name, 
4887                                                        strlen("Disposition-Notification-To: "),
4888                                                        TRUE);
4889                                 g_string_append_printf(header, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4890                         } else
4891                                 g_string_append_printf(header, "Disposition-Notification-To: %s\n", compose->account->address);
4892                 }
4893         }
4894
4895         /* get special headers */
4896         for (list = compose->header_list; list; list = list->next) {
4897                 ComposeHeaderEntry *headerentry;
4898                 gchar *tmp;
4899                 gchar *headername;
4900                 gchar *headername_wcolon;
4901                 gchar *headername_trans;
4902                 gchar *headervalue;
4903                 gchar **string;
4904                 gboolean standard_header = FALSE;
4905
4906                 headerentry = ((ComposeHeaderEntry *)list->data);
4907                 
4908                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4909                 if (strchr(tmp, ' ') != NULL || strchr(tmp, '\r') != NULL || strchr(tmp, '\n') != NULL) {
4910                         g_free(tmp);
4911                         continue;
4912                 }
4913
4914                 if (!strstr(tmp, ":")) {
4915                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4916                         headername = g_strdup(tmp);
4917                 } else {
4918                         headername_wcolon = g_strdup(tmp);
4919                         headername = g_strdup(strtok(tmp, ":"));
4920                 }
4921                 g_free(tmp);
4922                 
4923                 entry_str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4924                 Xstrdup_a(headervalue, entry_str, return NULL);
4925                 subst_char(headervalue, '\r', ' ');
4926                 subst_char(headervalue, '\n', ' ');
4927                 string = std_headers;
4928                 while (*string != NULL) {
4929                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4930                         if (!strcmp(headername_trans,headername_wcolon))
4931                                 standard_header = TRUE;
4932                         string++;
4933                 }
4934                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4935                         g_string_append_printf(header, "%s %s\n", headername_wcolon, headervalue);
4936                                 
4937                 g_free(headername);
4938                 g_free(headername_wcolon);              
4939         }
4940
4941         str = header->str;
4942         g_string_free(header, FALSE);
4943
4944         return str;
4945 }
4946
4947 #undef IS_IN_CUSTOM_HEADER
4948
4949 static void compose_convert_header(Compose *compose, gchar *dest, gint len, gchar *src,
4950                                    gint header_len, gboolean addr_field)
4951 {
4952         gchar *tmpstr = NULL;
4953         const gchar *out_codeset = NULL;
4954
4955         g_return_if_fail(src != NULL);
4956         g_return_if_fail(dest != NULL);
4957
4958         if (len < 1) return;
4959
4960         tmpstr = g_strdup(src);
4961
4962         subst_char(tmpstr, '\n', ' ');
4963         subst_char(tmpstr, '\r', ' ');
4964         g_strchomp(tmpstr);
4965
4966         if (!g_utf8_validate(tmpstr, -1, NULL)) {
4967                 gchar *mybuf = g_malloc(strlen(tmpstr)*2 +1);
4968                 conv_localetodisp(mybuf, strlen(tmpstr)*2 +1, tmpstr);
4969                 g_free(tmpstr);
4970                 tmpstr = mybuf;
4971         }
4972
4973         codeconv_set_strict(TRUE);
4974         conv_encode_header_full(dest, len, tmpstr, header_len, addr_field, 
4975                 conv_get_charset_str(compose->out_encoding));
4976         codeconv_set_strict(FALSE);
4977         
4978         if (!dest || *dest == '\0') {
4979                 gchar *test_conv_global_out = NULL;
4980                 gchar *test_conv_reply = NULL;
4981
4982                 /* automatic mode. be automatic. */
4983                 codeconv_set_strict(TRUE);
4984
4985                 out_codeset = conv_get_outgoing_charset_str();
4986                 if (out_codeset) {
4987                         debug_print("trying to convert to %s\n", out_codeset);
4988                         test_conv_global_out = conv_codeset_strdup(src, CS_INTERNAL, out_codeset);
4989                 }
4990
4991                 if (!test_conv_global_out && compose->orig_charset) {
4992                         out_codeset = compose->orig_charset;
4993                         debug_print("failure; trying to convert to %s\n", out_codeset);
4994                         test_conv_reply = conv_codeset_strdup(src, CS_INTERNAL, out_codeset);
4995                 }
4996
4997                 if (!test_conv_global_out && !test_conv_reply) {
4998                         /* we're lost */
4999                         out_codeset = CS_INTERNAL;
5000                         debug_print("finally using %s\n", out_codeset);
5001                 }
5002                 g_free(test_conv_global_out);
5003                 g_free(test_conv_reply);
5004                 conv_encode_header_full(dest, len, tmpstr, header_len, addr_field, 
5005                                         out_codeset);
5006                 codeconv_set_strict(FALSE);
5007         }
5008         g_free(tmpstr);
5009 }
5010
5011 static void compose_create_header_entry(Compose *compose) 
5012 {
5013         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
5014
5015         GtkWidget *combo;
5016         GtkWidget *entry;
5017         GList *combo_list = NULL;
5018         gchar **string;
5019         const gchar *header = NULL;
5020         ComposeHeaderEntry *headerentry;
5021         gboolean standard_header = FALSE;
5022
5023         headerentry = g_new0(ComposeHeaderEntry, 1);
5024
5025         /* Combo box */
5026         combo = gtk_combo_new();
5027         string = headers; 
5028         while(*string != NULL) {
5029                 combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
5030                 string++;
5031         }
5032         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
5033         g_list_free(combo_list);
5034         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
5035         g_signal_connect(G_OBJECT(GTK_COMBO(combo)->entry), "grab_focus",
5036                          G_CALLBACK(compose_grab_focus_cb), compose);
5037         gtk_widget_show(combo);
5038         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
5039         if (compose->header_last) {     
5040                 const gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
5041                 string = headers;
5042                 while (*string != NULL) {
5043                         if (!strcmp(*string, last_header_entry))
5044                                 standard_header = TRUE;
5045                         string++;
5046                 }
5047                 if (standard_header)
5048                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
5049         }
5050         if (!compose->header_last || !standard_header) {
5051                 switch(compose->account->protocol) {
5052                         case A_NNTP:
5053                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
5054                                 break;
5055                         default:
5056                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
5057                                 break;
5058                 }                                                                   
5059         }
5060         if (header)
5061                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
5062
5063         g_signal_connect_after(G_OBJECT(GTK_COMBO(combo)->entry), "grab_focus",
5064                          G_CALLBACK(compose_grab_focus_cb), compose);
5065
5066         /* Entry field */
5067         entry = gtk_entry_new(); 
5068         gtk_widget_show(entry);
5069         gtk_table_attach(GTK_TABLE(compose->header_table), entry, 1, 2, compose->header_nextrow, compose->header_nextrow+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
5070
5071         g_signal_connect(G_OBJECT(entry), "key-press-event", 
5072                          G_CALLBACK(compose_headerentry_key_press_event_cb), 
5073                          headerentry);
5074         g_signal_connect(G_OBJECT(entry), "changed", 
5075                          G_CALLBACK(compose_headerentry_changed_cb), 
5076                          headerentry);
5077         g_signal_connect_after(G_OBJECT(entry), "grab_focus",
5078                          G_CALLBACK(compose_grab_focus_cb), compose);
5079                          
5080         /* email dnd */
5081         gtk_drag_dest_set(entry, GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5082                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5083                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5084         g_signal_connect(G_OBJECT(entry), "drag_data_received",
5085                          G_CALLBACK(compose_header_drag_received_cb),
5086                          entry);
5087         g_signal_connect(G_OBJECT(entry), "drag-drop",
5088                          G_CALLBACK(compose_drag_drop),
5089                          compose);
5090         
5091         address_completion_register_entry(GTK_ENTRY(entry));
5092
5093         headerentry->compose = compose;
5094         headerentry->combo = combo;
5095         headerentry->entry = entry;
5096         headerentry->headernum = compose->header_nextrow;
5097
5098         compose->header_nextrow++;
5099         compose->header_last = headerentry;
5100 }
5101
5102 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
5103 {
5104         ComposeHeaderEntry *last_header;
5105         
5106         last_header = compose->header_last;
5107         
5108         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
5109         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
5110 }
5111
5112 static GtkWidget *compose_create_header(Compose *compose) 
5113 {
5114         GtkWidget *label;
5115         GtkWidget *hbox;
5116         GtkWidget *from_optmenu_hbox;
5117         GtkWidget *header_scrolledwin;
5118         GtkWidget *header_table;
5119
5120         gint count = 0;
5121
5122         /* header labels and entries */
5123         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
5124         gtk_widget_show(header_scrolledwin);
5125         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
5126
5127         header_table = gtk_table_new(2, 2, FALSE);
5128         gtk_widget_show(header_table);
5129         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
5130         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
5131         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
5132         count = 0;
5133
5134         /* option menu for selecting accounts */
5135         hbox = gtk_hbox_new(FALSE, 0);
5136         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
5137         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
5138         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
5139                          GTK_FILL, 0, 2, 0);
5140         from_optmenu_hbox = compose_account_option_menu_create(compose);
5141         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
5142                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
5143         count++;
5144
5145         compose->header_table = header_table;
5146         compose->header_list = NULL;
5147         compose->header_nextrow = count;
5148
5149         compose_create_header_entry(compose);
5150
5151         compose->table            = NULL;
5152
5153         return header_scrolledwin ;
5154 }
5155
5156 GtkWidget *compose_create_attach(Compose *compose)
5157 {
5158         GtkWidget *attach_scrwin;
5159         GtkWidget *attach_clist;
5160
5161         GtkListStore *store;
5162         GtkCellRenderer *renderer;
5163         GtkTreeViewColumn *column;
5164         GtkTreeSelection *selection;
5165
5166         /* attachment list */
5167         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
5168         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
5169                                        GTK_POLICY_AUTOMATIC,
5170                                        GTK_POLICY_AUTOMATIC);
5171         gtk_widget_set_size_request(attach_scrwin, -1, 80);
5172
5173         store = gtk_list_store_new(N_ATTACH_COLS, 
5174                                    G_TYPE_STRING,
5175                                    G_TYPE_STRING,
5176                                    G_TYPE_STRING,
5177                                    G_TYPE_POINTER,
5178                                    G_TYPE_AUTO_POINTER,
5179                                    -1);
5180         attach_clist = GTK_WIDGET(gtk_tree_view_new_with_model
5181                                         (GTK_TREE_MODEL(store)));
5182         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
5183         g_object_unref(store);
5184         
5185         renderer = gtk_cell_renderer_text_new();
5186         column = gtk_tree_view_column_new_with_attributes
5187                         (_("Mime type"), renderer, "text", 
5188                          COL_MIMETYPE, NULL);
5189         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);                        
5190         
5191         renderer = gtk_cell_renderer_text_new();
5192         column = gtk_tree_view_column_new_with_attributes
5193                         (_("Size"), renderer, "text", 
5194                          COL_SIZE, NULL);
5195         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);                        
5196         
5197         renderer = gtk_cell_renderer_text_new();
5198         column = gtk_tree_view_column_new_with_attributes
5199                         (_("Name"), renderer, "text", 
5200                          COL_NAME, NULL);
5201         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);
5202
5203         gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(attach_clist),
5204                                      prefs_common.enable_rules_hint);
5205         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(attach_clist));
5206         gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE);
5207
5208         g_signal_connect(G_OBJECT(attach_clist), "row_activated",
5209                          G_CALLBACK(attach_selected), compose);
5210         g_signal_connect(G_OBJECT(attach_clist), "button_press_event",
5211                          G_CALLBACK(attach_button_pressed), compose);
5212         g_signal_connect(G_OBJECT(attach_clist), "key_press_event",
5213                          G_CALLBACK(attach_key_pressed), compose);
5214
5215         /* drag and drop */
5216         gtk_drag_dest_set(attach_clist,
5217                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5218                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5219                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5220         g_signal_connect(G_OBJECT(attach_clist), "drag_data_received",
5221                          G_CALLBACK(compose_attach_drag_received_cb),
5222                          compose);
5223         g_signal_connect(G_OBJECT(attach_clist), "drag-drop",
5224                          G_CALLBACK(compose_drag_drop),
5225                          compose);
5226
5227         compose->attach_scrwin = attach_scrwin;
5228         compose->attach_clist  = attach_clist;
5229
5230         return attach_scrwin;
5231 }
5232
5233 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
5234 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
5235
5236 static GtkWidget *compose_create_others(Compose *compose)
5237 {
5238         GtkWidget *table;
5239         GtkWidget *savemsg_checkbtn;
5240         GtkWidget *savemsg_entry;
5241         GtkWidget *savemsg_select;
5242         
5243         guint rowcount = 0;
5244         gchar *folderidentifier;
5245
5246         /* Table for settings */
5247         table = gtk_table_new(3, 1, FALSE);
5248         gtk_widget_show(table);
5249         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
5250         rowcount = 0;
5251
5252         /* Save Message to folder */
5253         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
5254         gtk_widget_show(savemsg_checkbtn);
5255         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
5256         if (account_get_special_folder(compose->account, F_OUTBOX)) {
5257                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
5258         }
5259         g_signal_connect(G_OBJECT(savemsg_checkbtn), "toggled",
5260                          G_CALLBACK(compose_savemsg_checkbtn_cb), compose);
5261
5262         savemsg_entry = gtk_entry_new();
5263         gtk_widget_show(savemsg_entry);
5264         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
5265         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
5266         g_signal_connect_after(G_OBJECT(savemsg_entry), "grab_focus",
5267                          G_CALLBACK(compose_grab_focus_cb), compose);
5268         if (account_get_special_folder(compose->account, F_OUTBOX)) {
5269                 folderidentifier = folder_item_get_identifier(account_get_special_folder
5270                                   (compose->account, F_OUTBOX));
5271                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
5272                 g_free(folderidentifier);
5273         }
5274
5275         savemsg_select = gtkut_get_browse_file_btn(_("_Browse"));
5276         gtk_widget_show(savemsg_select);
5277         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
5278         g_signal_connect(G_OBJECT(savemsg_select), "clicked",
5279                          G_CALLBACK(compose_savemsg_select_cb),
5280                          compose);
5281
5282         rowcount++;
5283
5284         compose->savemsg_checkbtn = savemsg_checkbtn;
5285         compose->savemsg_entry = savemsg_entry;
5286
5287         return table;   
5288 }
5289
5290 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
5291 {
5292         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
5293                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
5294 }
5295
5296 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
5297 {
5298         FolderItem *dest;
5299         gchar * path;
5300
5301         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
5302         if (!dest) return;
5303
5304         path = folder_item_get_identifier(dest);
5305
5306         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
5307         g_free(path);
5308 }
5309
5310 static void entry_paste_clipboard(Compose *compose, GtkWidget *entry, gboolean wrap,
5311                                   GdkAtom clip);
5312
5313 #define BLOCK_WRAP() {                                                  \
5314         prev_autowrap = compose->autowrap;                              \
5315         buffer = gtk_text_view_get_buffer(                              \
5316                                         GTK_TEXT_VIEW(compose->text));  \
5317         compose->autowrap = FALSE;                                      \
5318                                                                         \
5319         g_signal_handlers_block_by_func(G_OBJECT(buffer),               \
5320                                 G_CALLBACK(compose_changed_cb),         \
5321                                 compose);                               \
5322         g_signal_handlers_block_by_func(G_OBJECT(buffer),               \
5323                                 G_CALLBACK(text_inserted),              \
5324                                 compose);                               \
5325 }
5326 #define UNBLOCK_WRAP() {                                                \
5327         compose->autowrap = prev_autowrap;                              \
5328         if (compose->autowrap)                                          \
5329                 compose_wrap_all(compose);                              \
5330                                                                         \
5331         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),             \
5332                                 G_CALLBACK(compose_changed_cb),         \
5333                                 compose);                               \
5334         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),             \
5335                                 G_CALLBACK(text_inserted),              \
5336                                 compose);                               \
5337 }
5338
5339
5340 static gboolean text_clicked(GtkWidget *text, GdkEventButton *event,
5341                                        Compose *compose)
5342 {
5343         gint prev_autowrap;
5344         GtkTextBuffer *buffer;
5345 #if USE_ASPELL
5346         if (event->button == 3) {
5347                 GtkTextIter iter;
5348                 GtkTextIter sel_start, sel_end;
5349                 gboolean stuff_selected;
5350                 gint x, y;
5351                 /* move the cursor to allow GtkAspell to check the word
5352                  * under the mouse */
5353                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(text),
5354                         GTK_TEXT_WINDOW_TEXT, event->x, event->y,
5355                         &x, &y);
5356                 gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW(text),
5357                         &iter, x, y);
5358                 /* get selection */
5359                 stuff_selected = gtk_text_buffer_get_selection_bounds(
5360                                 GTK_TEXT_VIEW(text)->buffer,
5361                                 &sel_start, &sel_end);
5362
5363                 gtk_text_buffer_place_cursor (GTK_TEXT_VIEW(text)->buffer, &iter);
5364                 /* reselect stuff */
5365                 if (stuff_selected 
5366                 && gtk_text_iter_in_range(&iter, &sel_start, &sel_end)) {
5367                         gtk_text_buffer_select_range(GTK_TEXT_VIEW(text)->buffer,
5368                                 &sel_start, &sel_end);
5369                 }
5370                 return FALSE; /* pass the event so that the right-click goes through */
5371         }
5372 #endif
5373         if (event->button == 2) {
5374                 BLOCK_WRAP();
5375                 entry_paste_clipboard(compose, compose->focused_editable, 
5376                                 prefs_common.linewrap_pastes,
5377                                 GDK_SELECTION_PRIMARY);
5378                 UNBLOCK_WRAP();
5379                 return TRUE;
5380         }
5381         return FALSE;
5382 }
5383
5384 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
5385 {
5386         Compose   *compose;
5387         GtkWidget *window;
5388         GtkWidget *vbox;
5389         GtkWidget *menubar;
5390         GtkWidget *handlebox;
5391
5392         GtkWidget *notebook;
5393
5394         GtkWidget *vbox2;
5395
5396         GtkWidget *label;
5397         GtkWidget *subject_hbox;
5398         GtkWidget *subject_frame;
5399         GtkWidget *subject_entry;
5400         GtkWidget *subject;
5401         GtkWidget *paned;
5402
5403         GtkWidget *edit_vbox;
5404         GtkWidget *ruler_hbox;
5405         GtkWidget *ruler;
5406         GtkWidget *scrolledwin;
5407         GtkWidget *text;
5408         GtkTextBuffer *buffer;
5409         GtkClipboard *clipboard;
5410
5411         UndoMain *undostruct;
5412
5413         gchar *titles[N_ATTACH_COLS];
5414         guint n_menu_entries;
5415         GdkColormap *cmap;
5416         GdkColor color[1];
5417         gboolean success[1];
5418         GtkWidget *popupmenu;
5419         GtkItemFactory *popupfactory;
5420         GtkItemFactory *ifactory;
5421         GtkWidget *tmpl_menu;
5422         gint n_entries;
5423         GtkWidget *menuitem;
5424
5425 #if USE_ASPELL
5426         GtkAspell * gtkaspell = NULL;
5427 #endif
5428
5429         static GdkGeometry geometry;
5430
5431         g_return_val_if_fail(account != NULL, NULL);
5432
5433         debug_print("Creating compose window...\n");
5434         compose = g_new0(Compose, 1);
5435
5436         titles[COL_MIMETYPE] = _("MIME type");
5437         titles[COL_SIZE]     = _("Size");
5438         titles[COL_NAME]     = _("Name");
5439
5440         compose->account = account;
5441         
5442         compose->mutex = g_mutex_new();
5443         compose->set_cursor_pos = -1;
5444
5445         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5446         gtk_window_set_resizable(GTK_WINDOW(window), TRUE);
5447         gtk_widget_set_size_request(window, -1, prefs_common.compose_height);
5448
5449         if (!geometry.max_width) {
5450                 geometry.max_width = gdk_screen_width();
5451                 geometry.max_height = gdk_screen_height();
5452         }
5453
5454         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
5455                                       &geometry, GDK_HINT_MAX_SIZE);
5456         if (!geometry.min_width) {
5457                 geometry.min_width = 600;
5458                 geometry.min_height = 480;
5459         }
5460         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
5461                                       &geometry, GDK_HINT_MIN_SIZE);
5462         gtk_widget_set_uposition(window, prefs_common.compose_x, 
5463                                  prefs_common.compose_y);
5464
5465         g_signal_connect(G_OBJECT(window), "delete_event",
5466                          G_CALLBACK(compose_delete_cb), compose);
5467         MANAGE_WINDOW_SIGNALS_CONNECT(window);
5468         gtk_widget_realize(window);
5469
5470         gtkut_widget_set_composer_icon(window);
5471
5472         vbox = gtk_vbox_new(FALSE, 0);
5473         gtk_container_add(GTK_CONTAINER(window), vbox);
5474
5475         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
5476         menubar = menubar_create(window, compose_entries,
5477                                  n_menu_entries, "<Compose>", compose);
5478         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
5479
5480         if (prefs_common.toolbar_detachable) {
5481                 handlebox = gtk_handle_box_new();
5482         } else {
5483                 handlebox = gtk_hbox_new(FALSE, 0);
5484         }
5485         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
5486
5487         gtk_widget_realize(handlebox);
5488         compose->toolbar = toolbar_create(TOOLBAR_COMPOSE, handlebox,
5489                                           (gpointer)compose);
5490
5491         vbox2 = gtk_vbox_new(FALSE, 2);
5492         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
5493         gtk_container_set_border_width(GTK_CONTAINER(vbox2), 0);
5494         
5495         /* Notebook */
5496         notebook = gtk_notebook_new();
5497         gtk_widget_set_size_request(notebook, -1, 130);
5498         gtk_widget_show(notebook);
5499
5500         /* header labels and entries */
5501         gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
5502                         compose_create_header(compose),
5503                         gtk_label_new_with_mnemonic(_("Hea_der")));
5504         /* attachment list */
5505         gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
5506                         compose_create_attach(compose),
5507                         gtk_label_new_with_mnemonic(_("_Attachments")));
5508         /* Others Tab */
5509         gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
5510                         compose_create_others(compose),
5511                         gtk_label_new_with_mnemonic(_("Othe_rs")));
5512
5513         /* Subject */
5514         subject_hbox = gtk_hbox_new(FALSE, 0);
5515         gtk_widget_show(subject_hbox);
5516
5517         subject_frame = gtk_frame_new(NULL);
5518         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_NONE);
5519         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, 0);
5520         gtk_widget_show(subject_frame);
5521
5522         subject = gtk_hbox_new(FALSE, 0);
5523         gtk_container_set_border_width(GTK_CONTAINER(subject), 0);
5524         gtk_widget_show(subject);
5525
5526         label = gtk_label_new(_("Subject:"));
5527         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 0);
5528         gtk_widget_show(label);
5529
5530         subject_entry = gtk_entry_new();
5531         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 0);
5532         g_signal_connect_after(G_OBJECT(subject_entry), "grab_focus",
5533                          G_CALLBACK(compose_grab_focus_cb), compose);
5534         gtk_widget_show(subject_entry);
5535         compose->subject_entry = subject_entry;
5536         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
5537         
5538         edit_vbox = gtk_vbox_new(FALSE, 0);
5539
5540         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
5541
5542         /* ruler */
5543         ruler_hbox = gtk_hbox_new(FALSE, 0);
5544         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
5545
5546         ruler = gtk_shruler_new();
5547         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
5548         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
5549                            BORDER_WIDTH);
5550
5551         /* text widget */
5552         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
5553         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
5554                                        GTK_POLICY_AUTOMATIC,
5555                                        GTK_POLICY_AUTOMATIC);
5556         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwin),
5557                                             GTK_SHADOW_IN);
5558         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
5559         gtk_widget_set_size_request(scrolledwin, prefs_common.compose_width, -1);
5560
5561         text = gtk_text_view_new();
5562         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
5563         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD_CHAR);
5564         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), TRUE);
5565         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
5566         gtk_text_buffer_add_selection_clipboard(buffer, clipboard);
5567         
5568         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
5569
5570         g_signal_connect_after(G_OBJECT(text), "size_allocate",
5571                                G_CALLBACK(compose_edit_size_alloc),
5572                                ruler);
5573         g_signal_connect(G_OBJECT(buffer), "changed",
5574                          G_CALLBACK(compose_changed_cb), compose);
5575         g_signal_connect(G_OBJECT(text), "grab_focus",
5576                          G_CALLBACK(compose_grab_focus_cb), compose);
5577         g_signal_connect(G_OBJECT(buffer), "insert_text",
5578                          G_CALLBACK(text_inserted), compose);
5579         g_signal_connect(G_OBJECT(text), "button_press_event",
5580                          G_CALLBACK(text_clicked), compose);
5581         g_signal_connect(G_OBJECT(subject_entry), "changed",
5582                          G_CALLBACK(compose_changed_cb), compose);
5583
5584         /* drag and drop */
5585         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5586                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5587                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5588         g_signal_connect(G_OBJECT(text), "drag_data_received",
5589                          G_CALLBACK(compose_insert_drag_received_cb),
5590                          compose);
5591         g_signal_connect(G_OBJECT(text), "drag-drop",
5592                          G_CALLBACK(compose_drag_drop),
5593                          compose);
5594         gtk_widget_show_all(vbox);
5595
5596         /* pane between attach clist and text */
5597         paned = gtk_vpaned_new();
5598         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
5599         gtk_container_add(GTK_CONTAINER(vbox2), paned);
5600         gtk_paned_add1(GTK_PANED(paned), notebook);
5601         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
5602         gtk_widget_show_all(paned);
5603
5604
5605         if (prefs_common.textfont) {
5606                 PangoFontDescription *font_desc;
5607
5608                 font_desc = pango_font_description_from_string
5609                         (prefs_common.textfont);
5610                 if (font_desc) {
5611                         gtk_widget_modify_font(text, font_desc);
5612                         pango_font_description_free(font_desc);
5613                 }
5614         }
5615
5616         color[0] = quote_color;
5617         cmap = gdk_drawable_get_colormap(window->window);
5618         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
5619         if (success[0] == FALSE) {
5620                 GtkStyle *style;
5621
5622                 g_warning("Compose: color allocation failed.\n");
5623                 style = gtk_widget_get_style(text);
5624                 quote_color = style->black;
5625         }
5626
5627         n_entries = sizeof(compose_popup_entries) /
5628                 sizeof(compose_popup_entries[0]);
5629         popupmenu = menu_create_items(compose_popup_entries, n_entries,
5630                                       "<Compose>", &popupfactory,
5631                                       compose);
5632
5633         ifactory = gtk_item_factory_from_widget(menubar);
5634         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5635         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5636         menu_set_sensitive(ifactory, "/Options/Remove references", FALSE);
5637
5638         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5639
5640         undostruct = undo_init(text);
5641         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
5642                                    menubar);
5643
5644         address_completion_start(window);
5645
5646         compose->window        = window;
5647         compose->vbox          = vbox;
5648         compose->menubar       = menubar;
5649         compose->handlebox     = handlebox;
5650
5651         compose->vbox2         = vbox2;
5652
5653         compose->paned = paned;
5654
5655         compose->edit_vbox     = edit_vbox;
5656         compose->ruler_hbox    = ruler_hbox;
5657         compose->ruler         = ruler;
5658         compose->scrolledwin   = scrolledwin;
5659         compose->text          = text;
5660
5661         compose->focused_editable = NULL;
5662
5663         compose->popupmenu    = popupmenu;
5664         compose->popupfactory = popupfactory;
5665
5666         compose->tmpl_menu = tmpl_menu;
5667
5668         compose->mode = mode;
5669
5670         compose->targetinfo = NULL;
5671         compose->replyinfo  = NULL;
5672         compose->fwdinfo    = NULL;
5673
5674         compose->replyto     = NULL;
5675         compose->cc          = NULL;
5676         compose->bcc         = NULL;
5677         compose->followup_to = NULL;
5678
5679         compose->ml_post     = NULL;
5680
5681         compose->inreplyto   = NULL;
5682         compose->references  = NULL;
5683         compose->msgid       = NULL;
5684         compose->boundary    = NULL;
5685
5686         compose->autowrap       = prefs_common.autowrap;
5687
5688         compose->use_signing    = FALSE;
5689         compose->use_encryption = FALSE;
5690         compose->privacy_system = NULL;
5691
5692         compose->modified = FALSE;
5693
5694         compose->return_receipt = FALSE;
5695
5696         compose->to_list        = NULL;
5697         compose->newsgroup_list = NULL;
5698
5699         compose->undostruct = undostruct;
5700
5701         compose->sig_str = NULL;
5702
5703         compose->exteditor_file    = NULL;
5704         compose->exteditor_pid     = -1;
5705         compose->exteditor_tag     = -1;
5706         compose->draft_timeout_tag = -1;
5707
5708 #if USE_ASPELL
5709         menu_set_sensitive(ifactory, "/Spelling", FALSE);
5710         if (mode != COMPOSE_REDIRECT) {
5711                 if (prefs_common.enable_aspell && prefs_common.dictionary &&
5712                     strcmp(prefs_common.dictionary, _("None"))) {
5713                         gtkaspell = gtkaspell_new(prefs_common.aspell_path,
5714                                                   prefs_common.dictionary,
5715                                                   conv_get_locale_charset_str(),
5716                                                   prefs_common.misspelled_col,
5717                                                   prefs_common.check_while_typing,
5718                                                   prefs_common.recheck_when_changing_dict,
5719                                                   prefs_common.use_alternate,
5720                                                   GTK_TEXT_VIEW(text),
5721                                                   GTK_WINDOW(compose->window));
5722                         if (!gtkaspell) {
5723                                 alertpanel_error(_("Spell checker could not "
5724                                                 "be started.\n%s"),
5725                                                 gtkaspell_checkers_strerror());
5726                                 gtkaspell_checkers_reset_error();
5727                         } else {
5728                                 if (!gtkaspell_set_sug_mode(gtkaspell,
5729                                                 prefs_common.aspell_sugmode)) {
5730                                         debug_print("Aspell: could not set "
5731                                                     "suggestion mode %s\n",
5732                                                     gtkaspell_checkers_strerror());
5733                                         gtkaspell_checkers_reset_error();
5734                                 }
5735
5736                                 menu_set_sensitive(ifactory, "/Spelling", TRUE);
5737                         }
5738                 }
5739         }
5740         compose->gtkaspell = gtkaspell;
5741 #endif
5742
5743         compose_select_account(compose, account, TRUE);
5744
5745         menu_set_active(ifactory, "/Edit/Auto wrapping", prefs_common.autowrap);
5746         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
5747                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
5748
5749         if (account->set_autobcc && account->auto_bcc && mode != COMPOSE_REEDIT) 
5750                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
5751         
5752         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
5753                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
5754
5755
5756         if (account->protocol != A_NNTP)
5757                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
5758         else
5759                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
5760
5761         addressbook_set_target_compose(compose);
5762         
5763         if (mode != COMPOSE_REDIRECT)
5764                 compose_set_template_menu(compose);
5765         else {
5766                 menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5767                 menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
5768         }
5769
5770         compose_list = g_list_append(compose_list, compose);
5771
5772         if (!prefs_common.show_ruler)
5773                 gtk_widget_hide(ruler_hbox);
5774                 
5775         menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Show ruler");
5776         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
5777                                        prefs_common.show_ruler);
5778
5779         /* Priority */
5780         compose->priority = PRIORITY_NORMAL;
5781         compose_update_priority_menu_item(compose);
5782
5783         compose_set_out_encoding(compose);
5784         
5785         /* Actions menu */
5786         compose_update_actions_menu(compose);
5787
5788         /* Privacy Systems menu */
5789         compose_update_privacy_systems_menu(compose);
5790
5791         activate_privacy_system(compose, account, TRUE);
5792         toolbar_set_style(compose->toolbar->toolbar, compose->handlebox, prefs_common.toolbar_style);
5793         gtk_widget_show(window);
5794         
5795         return compose;
5796 }
5797
5798 static GtkWidget *compose_account_option_menu_create(Compose *compose)
5799 {
5800         GList *accounts;
5801         GtkWidget *hbox;
5802         GtkWidget *optmenu;
5803         GtkWidget *menu;
5804         gint num = 0, def_menu = 0;
5805
5806         accounts = account_get_list();
5807         g_return_val_if_fail(accounts != NULL, NULL);
5808
5809         hbox = gtk_hbox_new(FALSE, 0);
5810         optmenu = gtk_option_menu_new();
5811         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5812         menu = gtk_menu_new();
5813
5814         for (; accounts != NULL; accounts = accounts->next, num++) {
5815                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
5816                 GtkWidget *menuitem;
5817                 gchar *name;
5818
5819                 if (ac == compose->account) def_menu = num;
5820
5821                 if (ac->name)
5822                         name = g_strdup_printf("%s: %s <%s>",
5823                                                ac->account_name,
5824                                                ac->name, ac->address);
5825                 else
5826                         name = g_strdup_printf("%s: %s",
5827                                                ac->account_name, ac->address);
5828                 MENUITEM_ADD(menu, menuitem, name, ac->account_id);
5829                 g_free(name);
5830                 g_signal_connect(G_OBJECT(menuitem), "activate",
5831                                  G_CALLBACK(account_activated),
5832                                  compose);
5833         }
5834
5835         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
5836         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
5837
5838         return hbox;
5839 }
5840
5841 static void compose_set_priority_cb(gpointer data,
5842                                     guint action,
5843                                     GtkWidget *widget)
5844 {
5845         Compose *compose = (Compose *) data;
5846         compose->priority = action;
5847 }
5848
5849 static void compose_update_priority_menu_item(Compose * compose)
5850 {
5851         GtkItemFactory *ifactory;
5852         GtkWidget *menuitem = NULL;
5853
5854         ifactory = gtk_item_factory_from_widget(compose->menubar);
5855         
5856         switch (compose->priority) {
5857                 case PRIORITY_HIGHEST:
5858                         menuitem = gtk_item_factory_get_item
5859                                 (ifactory, "/Options/Priority/Highest");
5860                         break;
5861                 case PRIORITY_HIGH:
5862                         menuitem = gtk_item_factory_get_item
5863                                 (ifactory, "/Options/Priority/High");
5864                         break;
5865                 case PRIORITY_NORMAL:
5866                         menuitem = gtk_item_factory_get_item
5867                                 (ifactory, "/Options/Priority/Normal");
5868                         break;
5869                 case PRIORITY_LOW:
5870                         menuitem = gtk_item_factory_get_item
5871                                 (ifactory, "/Options/Priority/Low");
5872                         break;
5873                 case PRIORITY_LOWEST:
5874                         menuitem = gtk_item_factory_get_item
5875                                 (ifactory, "/Options/Priority/Lowest");
5876                         break;
5877         }
5878         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5879 }       
5880
5881 static void compose_set_privacy_system_cb(GtkWidget *widget, gpointer data)
5882 {
5883         Compose *compose = (Compose *) data;
5884         gchar *systemid;
5885         GtkItemFactory *ifactory;
5886         gboolean can_sign = FALSE, can_encrypt = FALSE;
5887
5888         g_return_if_fail(GTK_IS_CHECK_MENU_ITEM(widget));
5889
5890         if (!GTK_CHECK_MENU_ITEM(widget)->active)
5891                 return;
5892
5893         systemid = g_object_get_data(G_OBJECT(widget), "privacy_system");
5894         g_free(compose->privacy_system);
5895         compose->privacy_system = NULL;
5896         if (systemid != NULL) {
5897                 compose->privacy_system = g_strdup(systemid);
5898
5899                 can_sign = privacy_system_can_sign(systemid);
5900                 can_encrypt = privacy_system_can_encrypt(systemid);
5901         }
5902
5903         debug_print("activated privacy system: %s\n", systemid != NULL ? systemid : "None");
5904
5905         ifactory = gtk_item_factory_from_widget(compose->menubar);
5906         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5907         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5908 }
5909
5910 static void compose_update_privacy_system_menu_item(Compose * compose, gboolean warn)
5911 {
5912         static gchar *branch_path = "/Options/Privacy System";
5913         GtkItemFactory *ifactory;
5914         GtkWidget *menuitem = NULL;
5915         GList *amenu;
5916         gboolean can_sign = FALSE, can_encrypt = FALSE;
5917         gboolean found = FALSE;
5918
5919         ifactory = gtk_item_factory_from_widget(compose->menubar);
5920
5921         if (compose->privacy_system != NULL) {
5922                 gchar *systemid;
5923
5924                 menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
5925                 g_return_if_fail(menuitem != NULL);
5926
5927                 amenu = GTK_MENU_SHELL(menuitem)->children;
5928                 menuitem = NULL;
5929                 while (amenu != NULL) {
5930                         GList *alist = amenu->next;
5931
5932                         systemid = g_object_get_data(G_OBJECT(amenu->data), "privacy_system");
5933                         if (systemid != NULL) {
5934                                 if (strcmp(systemid, compose->privacy_system) == 0) {
5935                                         menuitem = GTK_WIDGET(amenu->data);
5936
5937                                         can_sign = privacy_system_can_sign(systemid);
5938                                         can_encrypt = privacy_system_can_encrypt(systemid);
5939                                         found = TRUE;
5940                                         break;
5941                                 } 
5942                         } else if (strlen(compose->privacy_system) == 0) {
5943                                         menuitem = GTK_WIDGET(amenu->data);
5944
5945                                         can_sign = FALSE;
5946                                         can_encrypt = FALSE;
5947                                         found = TRUE;
5948                                         break;
5949                         }
5950
5951                         amenu = alist;
5952                 }
5953                 if (menuitem != NULL)
5954                         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5955                 
5956                 if (warn && !found && strlen(compose->privacy_system)) {
5957                         gchar *tmp = g_strdup_printf(
5958                                 _("The privacy system '%s' cannot be loaded. You "
5959                                   "will not be able to sign or encrypt this message."),
5960                                   compose->privacy_system);
5961                         alertpanel_warning(tmp);
5962                         g_free(tmp);
5963                 }
5964         } 
5965
5966         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5967         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5968 }       
5969  
5970 static void compose_set_out_encoding(Compose *compose)
5971 {
5972         GtkItemFactoryEntry *entry;
5973         GtkItemFactory *ifactory;
5974         CharSet out_encoding;
5975         gchar *path, *p, *q;
5976         GtkWidget *item;
5977
5978         out_encoding = conv_get_charset_from_str(prefs_common.outgoing_charset);
5979         ifactory = gtk_item_factory_from_widget(compose->menubar);
5980
5981         for (entry = compose_entries; entry->callback != compose_address_cb;
5982              entry++) {
5983                 if (entry->callback == compose_set_encoding_cb &&
5984                     (CharSet)entry->callback_action == out_encoding) {
5985                         p = q = path = g_strdup(entry->path);
5986                         while (*p) {
5987                                 if (*p == '_') {
5988                                         if (p[1] == '_') {
5989                                                 p++;
5990                                                 *q++ = '_';
5991                                         }
5992                                 } else
5993                                         *q++ = *p;
5994                                 p++;
5995                         }
5996                         *q = '\0';
5997                         item = gtk_item_factory_get_item(ifactory, path);
5998                         gtk_widget_activate(item);
5999                         g_free(path);
6000                         break;
6001                 }
6002         }
6003 }
6004
6005 static void compose_set_template_menu(Compose *compose)
6006 {
6007         GSList *tmpl_list, *cur;
6008         GtkWidget *menu;
6009         GtkWidget *item;
6010
6011         tmpl_list = template_get_config();
6012
6013         menu = gtk_menu_new();
6014
6015         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
6016                 Template *tmpl = (Template *)cur->data;
6017
6018                 item = gtk_menu_item_new_with_label(tmpl->name);
6019                 gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
6020                 g_signal_connect(G_OBJECT(item), "activate",
6021                                  G_CALLBACK(compose_template_activate_cb),
6022                                  compose);
6023                 g_object_set_data(G_OBJECT(item), "template", tmpl);
6024                 gtk_widget_show(item);
6025         }
6026
6027         gtk_widget_show(menu);
6028         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
6029 }
6030
6031 void compose_update_actions_menu(Compose *compose)
6032 {
6033         GtkItemFactory *ifactory;
6034
6035         ifactory = gtk_item_factory_from_widget(compose->menubar);
6036         action_update_compose_menu(ifactory, "/Tools/Actions", compose);
6037 }
6038
6039 void compose_update_privacy_systems_menu(Compose *compose)
6040 {
6041         static gchar *branch_path = "/Options/Privacy System";
6042         GtkItemFactory *ifactory;
6043         GtkWidget *menuitem;
6044         GSList *systems, *cur;
6045         GList *amenu;
6046         GtkWidget *widget;
6047         GtkWidget *system_none;
6048         GSList *group;
6049
6050         ifactory = gtk_item_factory_from_widget(compose->menubar);
6051
6052         /* remove old entries */
6053         menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
6054         g_return_if_fail(menuitem != NULL);
6055
6056         amenu = GTK_MENU_SHELL(menuitem)->children->next;
6057         while (amenu != NULL) {
6058                 GList *alist = amenu->next;
6059                 gtk_widget_destroy(GTK_WIDGET(amenu->data));
6060                 amenu = alist;
6061         }
6062
6063         system_none = gtk_item_factory_get_widget(ifactory,
6064                 "/Options/Privacy System/None");
6065
6066         g_signal_connect(G_OBJECT(system_none), "activate",
6067                 G_CALLBACK(compose_set_privacy_system_cb), compose);
6068
6069         systems = privacy_get_system_ids();
6070         for (cur = systems; cur != NULL; cur = g_slist_next(cur)) {
6071                 gchar *systemid = cur->data;
6072
6073                 group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(system_none));
6074                 widget = gtk_radio_menu_item_new_with_label(group,
6075                         privacy_system_get_name(systemid));
6076                 g_object_set_data_full(G_OBJECT(widget), "privacy_system",
6077                                        g_strdup(systemid), g_free);
6078                 g_signal_connect(G_OBJECT(widget), "activate",
6079                         G_CALLBACK(compose_set_privacy_system_cb), compose);
6080
6081                 gtk_menu_append(GTK_MENU(system_none->parent), widget);
6082                 gtk_widget_show(widget);
6083                 g_free(systemid);
6084         }
6085         g_slist_free(systems);
6086 }
6087
6088 void compose_reflect_prefs_all(void)
6089 {
6090         GList *cur;
6091         Compose *compose;
6092
6093         for (cur = compose_list; cur != NULL; cur = cur->next) {
6094                 compose = (Compose *)cur->data;
6095                 compose_set_template_menu(compose);
6096         }
6097 }
6098
6099 void compose_reflect_prefs_pixmap_theme(void)
6100 {
6101         GList *cur;
6102         Compose *compose;
6103
6104         for (cur = compose_list; cur != NULL; cur = cur->next) {
6105                 compose = (Compose *)cur->data;
6106                 toolbar_update(TOOLBAR_COMPOSE, compose);
6107         }
6108 }
6109
6110 static void compose_template_apply(Compose *compose, Template *tmpl,
6111                                    gboolean replace)
6112 {
6113         GtkTextView *text;
6114         GtkTextBuffer *buffer;
6115         GtkTextMark *mark;
6116         GtkTextIter iter;
6117         gchar *qmark;
6118         gchar *parsed_str = NULL;
6119         gint cursor_pos = 0;
6120         if (!tmpl) return;
6121
6122         /* process the body */
6123
6124         text = GTK_TEXT_VIEW(compose->text);
6125         buffer = gtk_text_view_get_buffer(text);
6126
6127         if (replace)
6128                 gtk_text_buffer_set_text(buffer, "", -1);
6129
6130         mark = gtk_text_buffer_get_insert(buffer);
6131         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
6132
6133         if (tmpl->value) {
6134                 if ((compose->replyinfo == NULL) && (compose->fwdinfo == NULL)) {
6135                         parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
6136                                                        NULL, NULL, FALSE);
6137                 } else {
6138                         if (prefs_common.quotemark && *prefs_common.quotemark)
6139                                 qmark = prefs_common.quotemark;
6140                         else
6141                                 qmark = "> ";
6142
6143                         if (compose->replyinfo != NULL)
6144                                 parsed_str = compose_quote_fmt(compose, compose->replyinfo,
6145                                                                tmpl->value, qmark, NULL, FALSE);
6146                         else if (compose->fwdinfo != NULL)
6147                                 parsed_str = compose_quote_fmt(compose, compose->fwdinfo,
6148                                                                tmpl->value, qmark, NULL, FALSE);
6149                         else
6150                                 parsed_str = NULL;
6151                 }
6152         }
6153         if (replace && parsed_str && compose->account->auto_sig)
6154                 compose_insert_sig(compose, FALSE);
6155
6156         if (replace && parsed_str) {
6157                 gtk_text_buffer_get_start_iter(buffer, &iter);
6158                 gtk_text_buffer_place_cursor(buffer, &iter);
6159         }
6160         
6161         if (parsed_str) {
6162                 cursor_pos = quote_fmt_get_cursor_pos();
6163                 compose->set_cursor_pos = cursor_pos;
6164                 if (cursor_pos == -1)
6165                         cursor_pos = 0;
6166                 gtk_text_buffer_get_start_iter(buffer, &iter);
6167                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, cursor_pos);
6168                 gtk_text_buffer_place_cursor(buffer, &iter);
6169         }
6170
6171         /* process the other fields */
6172         compose_template_apply_fields(compose, tmpl);
6173         
6174         compose_changed_cb(NULL, compose);
6175 }
6176
6177 void compose_template_apply_fields(Compose *compose, Template *tmpl)
6178 {
6179         static MsgInfo dummyinfo;
6180         MsgInfo *msginfo = NULL;
6181         gchar *buf = NULL;
6182
6183         if (compose->replyinfo != NULL)
6184                 msginfo = compose->replyinfo;
6185         else if (compose->fwdinfo != NULL)
6186                 msginfo = compose->fwdinfo;
6187         else
6188                 msginfo = &dummyinfo;
6189
6190         if (tmpl->to && *tmpl->to != '\0') {
6191                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
6192                 quote_fmt_scan_string(tmpl->to);
6193                 quote_fmt_parse();
6194
6195                 buf = quote_fmt_get_buffer();
6196                 if (buf == NULL) {
6197                         alertpanel_error(_("Message To format error."));
6198                 } else {
6199                         compose_entry_append(compose, buf, COMPOSE_TO);
6200                 }
6201         }
6202
6203         if (tmpl->cc && *tmpl->cc != '\0') {
6204                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
6205                 quote_fmt_scan_string(tmpl->cc);
6206                 quote_fmt_parse();
6207
6208                 buf = quote_fmt_get_buffer();
6209                 if (buf == NULL) {
6210                         alertpanel_error(_("Message Cc format error."));
6211                 } else {
6212                         compose_entry_append(compose, buf, COMPOSE_CC);
6213                 }
6214         }
6215
6216         if (tmpl->bcc && *tmpl->bcc != '\0') {
6217                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
6218                 quote_fmt_scan_string(tmpl->bcc);
6219                 quote_fmt_parse();
6220
6221                 buf = quote_fmt_get_buffer();
6222                 if (buf == NULL) {
6223                         alertpanel_error(_("Message Bcc format error."));
6224                 } else {
6225                         compose_entry_append(compose, buf, COMPOSE_BCC);
6226                 }
6227         }
6228
6229         /* process the subject */
6230         if (tmpl->subject && *tmpl->subject != '\0') {
6231                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
6232                 quote_fmt_scan_string(tmpl->subject);
6233                 quote_fmt_parse();
6234
6235                 buf = quote_fmt_get_buffer();
6236                 if (buf == NULL) {
6237                         alertpanel_error(_("Message subject format error."));
6238                 } else {
6239                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf);
6240                 }
6241         }
6242 }
6243
6244 static void compose_destroy(Compose *compose)
6245 {
6246         compose_list = g_list_remove(compose_list, compose);
6247
6248         /* NOTE: address_completion_end() does nothing with the window
6249          * however this may change. */
6250         address_completion_end(compose->window);
6251
6252         slist_free_strings(compose->to_list);
6253         g_slist_free(compose->to_list);
6254         slist_free_strings(compose->newsgroup_list);
6255         g_slist_free(compose->newsgroup_list);
6256         slist_free_strings(compose->header_list);
6257         g_slist_free(compose->header_list);
6258
6259         procmsg_msginfo_free(compose->targetinfo);
6260         procmsg_msginfo_free(compose->replyinfo);
6261         procmsg_msginfo_free(compose->fwdinfo);
6262
6263         g_free(compose->replyto);
6264         g_free(compose->cc);
6265         g_free(compose->bcc);
6266         g_free(compose->newsgroups);
6267         g_free(compose->followup_to);
6268
6269         g_free(compose->ml_post);
6270
6271         g_free(compose->inreplyto);
6272         g_free(compose->references);
6273         g_free(compose->msgid);
6274         g_free(compose->boundary);
6275
6276         if (compose->redirect_filename)
6277                 g_free(compose->redirect_filename);
6278         if (compose->undostruct)
6279                 undo_destroy(compose->undostruct);
6280
6281         g_free(compose->sig_str);
6282
6283         g_free(compose->exteditor_file);
6284
6285         g_free(compose->orig_charset);
6286
6287         g_free(compose->privacy_system);
6288
6289         if (addressbook_get_target_compose() == compose)
6290                 addressbook_set_target_compose(NULL);
6291
6292 #if USE_ASPELL
6293         if (compose->gtkaspell) {
6294                 gtkaspell_delete(compose->gtkaspell);
6295                 compose->gtkaspell = NULL;
6296         }
6297 #endif
6298
6299         prefs_common.compose_width = compose->scrolledwin->allocation.width;
6300         prefs_common.compose_height = compose->window->allocation.height;
6301
6302         if (!gtk_widget_get_parent(compose->paned))
6303                 gtk_widget_destroy(compose->paned);
6304         gtk_widget_destroy(compose->popupmenu);
6305
6306         gtk_widget_destroy(compose->window);
6307         toolbar_destroy(compose->toolbar);
6308         g_free(compose->toolbar);
6309         g_mutex_free(compose->mutex);
6310         g_free(compose);
6311 }
6312
6313 static void compose_attach_info_free(AttachInfo *ainfo)
6314 {
6315         g_free(ainfo->file);
6316         g_free(ainfo->content_type);
6317         g_free(ainfo->name);
6318         g_free(ainfo);
6319 }
6320
6321 static void compose_attach_remove_selected(Compose *compose)
6322 {
6323         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
6324         GtkTreeSelection *selection;
6325         GList *sel, *cur;
6326         GtkTreeModel *model;
6327
6328         selection = gtk_tree_view_get_selection(tree_view);
6329         sel = gtk_tree_selection_get_selected_rows(selection, &model);
6330
6331         if (!sel) 
6332                 return;
6333
6334         for (cur = sel; cur != NULL; cur = cur->next) {
6335                 GtkTreePath *path = cur->data;
6336                 GtkTreeRowReference *ref = gtk_tree_row_reference_new
6337                                                 (model, cur->data);
6338                 cur->data = ref;
6339                 gtk_tree_path_free(path);
6340         }
6341
6342         for (cur = sel; cur != NULL; cur = cur->next) {
6343                 GtkTreeRowReference *ref = cur->data;
6344                 GtkTreePath *path = gtk_tree_row_reference_get_path(ref);
6345                 GtkTreeIter iter;
6346
6347                 if (gtk_tree_model_get_iter(model, &iter, path))
6348                         gtk_list_store_remove(GTK_LIST_STORE(model), &iter);
6349                 
6350                 gtk_tree_path_free(path);
6351                 gtk_tree_row_reference_free(ref);
6352         }
6353
6354         g_list_free(sel);
6355 }
6356
6357 static struct _AttachProperty
6358 {
6359         GtkWidget *window;
6360         GtkWidget *mimetype_entry;
6361         GtkWidget *encoding_optmenu;
6362         GtkWidget *path_entry;
6363         GtkWidget *filename_entry;
6364         GtkWidget *ok_btn;
6365         GtkWidget *cancel_btn;
6366 } attach_prop;
6367
6368 static void gtk_tree_path_free_(gpointer ptr, gpointer data)
6369 {       
6370         gtk_tree_path_free((GtkTreePath *)ptr);
6371 }
6372
6373 static void compose_attach_property(Compose *compose)
6374 {
6375         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
6376         AttachInfo *ainfo;
6377         GtkOptionMenu *optmenu;
6378         GtkTreeSelection *selection;
6379         GList *sel;
6380         GtkTreeModel *model;
6381         GtkTreeIter iter;
6382         GtkTreePath *path;
6383         static gboolean cancelled;
6384
6385         /* only if one selected */
6386         selection = gtk_tree_view_get_selection(tree_view);
6387         if (gtk_tree_selection_count_selected_rows(selection) != 1) 
6388                 return;
6389
6390         sel = gtk_tree_selection_get_selected_rows(selection, &model);
6391         if (!sel)
6392                 return;
6393
6394         path = (GtkTreePath *) sel->data;
6395         gtk_tree_model_get_iter(model, &iter, path);
6396         gtk_tree_model_get(model, &iter, COL_DATA, &ainfo, -1); 
6397         
6398         if (!ainfo) {
6399                 g_list_foreach(sel, gtk_tree_path_free_, NULL);
6400                 g_list_free(sel);
6401                 return;
6402         }               
6403         g_list_free(sel);
6404
6405         if (!attach_prop.window)
6406                 compose_attach_property_create(&cancelled);
6407         gtk_widget_grab_focus(attach_prop.ok_btn);
6408         gtk_widget_show(attach_prop.window);
6409         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
6410
6411         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
6412         if (ainfo->encoding == ENC_UNKNOWN)
6413                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
6414                                     GINT_TO_POINTER(ENC_BASE64));
6415         else
6416                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
6417                                     GINT_TO_POINTER(ainfo->encoding));
6418
6419         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
6420                            ainfo->content_type ? ainfo->content_type : "");
6421         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
6422                            ainfo->file ? ainfo->file : "");
6423         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
6424                            ainfo->name ? ainfo->name : "");
6425
6426         for (;;) {
6427                 const gchar *entry_text;
6428                 gchar *text;
6429                 gchar *cnttype = NULL;
6430                 gchar *file = NULL;
6431                 off_t size = 0;
6432                 GtkWidget *menu;
6433                 GtkWidget *menuitem;
6434
6435                 cancelled = FALSE;
6436                 gtk_main();
6437
6438                 gtk_widget_hide(attach_prop.window);
6439                 
6440                 if (cancelled) 
6441                         break;
6442
6443                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
6444                 if (*entry_text != '\0') {
6445                         gchar *p;
6446
6447                         text = g_strstrip(g_strdup(entry_text));
6448                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
6449                                 cnttype = g_strdup(text);
6450                                 g_free(text);
6451                         } else {
6452                                 alertpanel_error(_("Invalid MIME type."));
6453                                 g_free(text);
6454                                 continue;
6455                         }
6456                 }
6457
6458                 menu = gtk_option_menu_get_menu(optmenu);
6459                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
6460                 ainfo->encoding = GPOINTER_TO_INT
6461                         (g_object_get_data(G_OBJECT(menuitem), MENU_VAL_ID));
6462
6463                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
6464                 if (*entry_text != '\0') {
6465                         if (is_file_exist(entry_text) &&
6466                             (size = get_file_size(entry_text)) > 0)
6467                                 file = g_strdup(entry_text);
6468                         else {
6469                                 alertpanel_error
6470                                         (_("File doesn't exist or is empty."));
6471                                 g_free(cnttype);
6472                                 continue;
6473                         }
6474                 }
6475
6476                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
6477                 if (*entry_text != '\0') {
6478                         g_free(ainfo->name);
6479                         ainfo->name = g_strdup(entry_text);
6480                 }
6481
6482                 if (cnttype) {
6483                         g_free(ainfo->content_type);
6484                         ainfo->content_type = cnttype;
6485                 }
6486                 if (file) {
6487                         g_free(ainfo->file);
6488                         ainfo->file = file;
6489                 }
6490                 if (size)
6491                         ainfo->size = size;
6492
6493                 /* update tree store */
6494                 text = to_human_readable(ainfo->size);
6495                 gtk_tree_model_get_iter(model, &iter, path);
6496                 gtk_list_store_set(GTK_LIST_STORE(model), &iter,
6497                                    COL_MIMETYPE, ainfo->content_type,
6498                                    COL_SIZE, text,
6499                                    COL_NAME, ainfo->name,
6500                                    -1);
6501                 
6502                 break;
6503         }
6504
6505         gtk_tree_path_free(path);
6506 }
6507
6508 #define SET_LABEL_AND_ENTRY(str, entry, top) \
6509 { \
6510         label = gtk_label_new(str); \
6511         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
6512                          GTK_FILL, 0, 0, 0); \
6513         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
6514  \
6515         entry = gtk_entry_new(); \
6516         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
6517                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
6518 }
6519
6520 static void compose_attach_property_create(gboolean *cancelled)
6521 {
6522         GtkWidget *window;
6523         GtkWidget *vbox;
6524         GtkWidget *table;
6525         GtkWidget *label;
6526         GtkWidget *mimetype_entry;
6527         GtkWidget *hbox;
6528         GtkWidget *optmenu;
6529         GtkWidget *optmenu_menu;
6530         GtkWidget *menuitem;
6531         GtkWidget *path_entry;
6532         GtkWidget *filename_entry;
6533         GtkWidget *hbbox;
6534         GtkWidget *ok_btn;
6535         GtkWidget *cancel_btn;
6536         GList     *mime_type_list, *strlist;
6537
6538         debug_print("Creating attach_property window...\n");
6539
6540         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
6541         gtk_widget_set_size_request(window, 480, -1);
6542         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
6543         gtk_window_set_title(GTK_WINDOW(window), _("Properties"));
6544         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
6545         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
6546         g_signal_connect(G_OBJECT(window), "delete_event",
6547                          G_CALLBACK(attach_property_delete_event),
6548                          cancelled);
6549         g_signal_connect(G_OBJECT(window), "key_press_event",
6550                          G_CALLBACK(attach_property_key_pressed),
6551                          cancelled);
6552
6553         vbox = gtk_vbox_new(FALSE, 8);
6554         gtk_container_add(GTK_CONTAINER(window), vbox);
6555
6556         table = gtk_table_new(4, 2, FALSE);
6557         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
6558         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
6559         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
6560
6561         label = gtk_label_new(_("MIME type")); 
6562         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
6563                          GTK_FILL, 0, 0, 0); 
6564         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
6565         mimetype_entry = gtk_combo_new(); 
6566         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
6567                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
6568                          
6569         /* stuff with list */
6570         mime_type_list = procmime_get_mime_type_list();
6571         strlist = NULL;
6572         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
6573                 MimeType *type = (MimeType *) mime_type_list->data;
6574                 gchar *tmp;
6575
6576                 tmp = g_strdup_printf("%s/%s", type->type, type->sub_type);
6577
6578                 if (g_list_find_custom(strlist, tmp, (GCompareFunc)strcmp2))
6579                         g_free(tmp);
6580                 else
6581                         strlist = g_list_insert_sorted(strlist, (gpointer)tmp,
6582                                         (GCompareFunc)strcmp2);
6583         }
6584
6585         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
6586
6587         for (mime_type_list = strlist; mime_type_list != NULL; 
6588                 mime_type_list = mime_type_list->next)
6589                 g_free(mime_type_list->data);
6590         g_list_free(strlist);
6591                          
6592         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
6593
6594         label = gtk_label_new(_("Encoding"));
6595         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
6596                          GTK_FILL, 0, 0, 0);
6597         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
6598
6599         hbox = gtk_hbox_new(FALSE, 0);
6600         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
6601                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
6602
6603         optmenu = gtk_option_menu_new();
6604         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
6605
6606         optmenu_menu = gtk_menu_new();
6607         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
6608         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6609         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
6610         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6611         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable",
6612                      ENC_QUOTED_PRINTABLE);
6613         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6614
6615         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
6616
6617         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6618
6619         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
6620         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
6621
6622         gtkut_stock_button_set_create(&hbbox, &cancel_btn, GTK_STOCK_CANCEL,
6623                                       &ok_btn, GTK_STOCK_OK,
6624                                       NULL, NULL);
6625         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
6626         gtk_widget_grab_default(ok_btn);
6627
6628         g_signal_connect(G_OBJECT(ok_btn), "clicked",
6629                          G_CALLBACK(attach_property_ok),
6630                          cancelled);
6631         g_signal_connect(G_OBJECT(cancel_btn), "clicked",
6632                          G_CALLBACK(attach_property_cancel),
6633                          cancelled);
6634
6635         gtk_widget_show_all(vbox);
6636
6637         attach_prop.window           = window;
6638         attach_prop.mimetype_entry   = mimetype_entry;
6639         attach_prop.encoding_optmenu = optmenu;
6640         attach_prop.path_entry       = path_entry;
6641         attach_prop.filename_entry   = filename_entry;
6642         attach_prop.ok_btn           = ok_btn;
6643         attach_prop.cancel_btn       = cancel_btn;
6644 }
6645
6646 #undef SET_LABEL_AND_ENTRY
6647
6648 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
6649 {
6650         *cancelled = FALSE;
6651         gtk_main_quit();
6652 }
6653
6654 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
6655 {
6656         *cancelled = TRUE;
6657         gtk_main_quit();
6658 }
6659
6660 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
6661                                          gboolean *cancelled)
6662 {
6663         *cancelled = TRUE;
6664         gtk_main_quit();
6665
6666         return TRUE;
6667 }
6668
6669 static gboolean attach_property_key_pressed(GtkWidget *widget,
6670                                             GdkEventKey *event,
6671                                             gboolean *cancelled)
6672 {
6673         if (event && event->keyval == GDK_Escape) {
6674                 *cancelled = TRUE;
6675                 gtk_main_quit();
6676         }
6677         return FALSE;
6678 }
6679
6680 static void compose_exec_ext_editor(Compose *compose)
6681 {
6682 #ifdef G_OS_UNIX
6683         gchar *tmp;
6684         pid_t pid;
6685         gint pipe_fds[2];
6686
6687         tmp = g_strdup_printf("%s%ctmpmsg.%p", get_tmp_dir(),
6688                               G_DIR_SEPARATOR, compose);
6689
6690         if (pipe(pipe_fds) < 0) {
6691                 perror("pipe");
6692                 g_free(tmp);
6693                 return;
6694         }
6695
6696         if ((pid = fork()) < 0) {
6697                 perror("fork");
6698                 g_free(tmp);
6699                 return;
6700         }
6701
6702         if (pid != 0) {
6703                 /* close the write side of the pipe */
6704                 close(pipe_fds[1]);
6705
6706                 compose->exteditor_file    = g_strdup(tmp);
6707                 compose->exteditor_pid     = pid;
6708
6709                 compose_set_ext_editor_sensitive(compose, FALSE);
6710
6711                 compose->exteditor_ch = g_io_channel_unix_new(pipe_fds[0]);
6712                 compose->exteditor_tag = g_io_add_watch(compose->exteditor_ch,
6713                                                         G_IO_IN,
6714                                                         compose_input_cb,
6715                                                         compose);
6716         } else {        /* process-monitoring process */
6717                 pid_t pid_ed;
6718
6719                 if (setpgid(0, 0))
6720                         perror("setpgid");
6721
6722                 /* close the read side of the pipe */
6723                 close(pipe_fds[0]);
6724
6725                 if (compose_write_body_to_file(compose, tmp) < 0) {
6726                         fd_write_all(pipe_fds[1], "2\n", 2);
6727                         _exit(1);
6728                 }
6729
6730                 pid_ed = compose_exec_ext_editor_real(tmp);
6731                 if (pid_ed < 0) {
6732                         fd_write_all(pipe_fds[1], "1\n", 2);
6733                         _exit(1);
6734                 }
6735
6736                 /* wait until editor is terminated */
6737                 waitpid(pid_ed, NULL, 0);
6738
6739                 fd_write_all(pipe_fds[1], "0\n", 2);
6740
6741                 close(pipe_fds[1]);
6742                 _exit(0);
6743         }
6744
6745         g_free(tmp);
6746 #endif /* G_OS_UNIX */
6747 }
6748
6749 #ifdef G_OS_UNIX
6750 static gint compose_exec_ext_editor_real(const gchar *file)
6751 {
6752         gchar buf[1024];
6753         gchar *p;
6754         gchar **cmdline;
6755         pid_t pid;
6756
6757         g_return_val_if_fail(file != NULL, -1);
6758
6759         if ((pid = fork()) < 0) {
6760                 perror("fork");
6761                 return -1;
6762         }
6763
6764         if (pid != 0) return pid;
6765
6766         /* grandchild process */
6767
6768         if (setpgid(0, getppid()))
6769                 perror("setpgid");
6770
6771         if (prefs_common.ext_editor_cmd &&
6772             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
6773             *(p + 1) == 's' && !strchr(p + 2, '%')) {
6774                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
6775         } else {
6776                 if (prefs_common.ext_editor_cmd)
6777                         g_warning("External editor command line is invalid: '%s'\n",
6778                                   prefs_common.ext_editor_cmd);
6779                 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, file);
6780         }
6781
6782         cmdline = strsplit_with_quote(buf, " ", 1024);
6783         execvp(cmdline[0], cmdline);
6784
6785         perror("execvp");
6786         g_strfreev(cmdline);
6787
6788         _exit(1);
6789 }
6790
6791 static gboolean compose_ext_editor_kill(Compose *compose)
6792 {
6793         pid_t pgid = compose->exteditor_pid * -1;
6794         gint ret;
6795
6796         ret = kill(pgid, 0);
6797
6798         if (ret == 0 || (ret == -1 && EPERM == errno)) {
6799                 AlertValue val;
6800                 gchar *msg;
6801
6802                 msg = g_strdup_printf
6803                         (_("The external editor is still working.\n"
6804                            "Force terminating the process?\n"
6805                            "process group id: %d"), -pgid);
6806                 val = alertpanel_full(_("Notice"), msg, GTK_STOCK_NO, GTK_STOCK_YES,
6807                                       NULL, FALSE, NULL, ALERT_WARNING, G_ALERTDEFAULT);
6808                         
6809                 g_free(msg);
6810
6811                 if (val == G_ALERTALTERNATE) {
6812                         g_source_remove(compose->exteditor_tag);
6813                         g_io_channel_shutdown(compose->exteditor_ch,
6814                                               FALSE, NULL);
6815                         g_io_channel_unref(compose->exteditor_ch);
6816
6817                         if (kill(pgid, SIGTERM) < 0) perror("kill");
6818                         waitpid(compose->exteditor_pid, NULL, 0);
6819
6820                         g_warning("Terminated process group id: %d", -pgid);
6821                         g_warning("Temporary file: %s",
6822                                   compose->exteditor_file);
6823
6824                         compose_set_ext_editor_sensitive(compose, TRUE);
6825
6826                         g_free(compose->exteditor_file);
6827                         compose->exteditor_file    = NULL;
6828                         compose->exteditor_pid     = -1;
6829                         compose->exteditor_ch      = NULL;
6830                         compose->exteditor_tag     = -1;
6831                 } else
6832                         return FALSE;
6833         }
6834
6835         return TRUE;
6836 }
6837
6838 static gboolean compose_input_cb(GIOChannel *source, GIOCondition condition,
6839                                  gpointer data)
6840 {
6841         gchar buf[3] = "3";
6842         Compose *compose = (Compose *)data;
6843         gsize bytes_read;
6844
6845         debug_print(_("Compose: input from monitoring process\n"));
6846
6847         g_io_channel_read_chars(source, buf, sizeof(buf), &bytes_read, NULL);
6848
6849         g_io_channel_shutdown(source, FALSE, NULL);
6850         g_io_channel_unref(source);
6851
6852         waitpid(compose->exteditor_pid, NULL, 0);
6853
6854         if (buf[0] == '0') {            /* success */
6855                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
6856                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
6857
6858                 gtk_text_buffer_set_text(buffer, "", -1);
6859                 compose_insert_file(compose, compose->exteditor_file);
6860                 compose_changed_cb(NULL, compose);
6861
6862                 if (g_unlink(compose->exteditor_file) < 0)
6863                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
6864         } else if (buf[0] == '1') {     /* failed */
6865                 g_warning("Couldn't exec external editor\n");
6866                 if (g_unlink(compose->exteditor_file) < 0)
6867                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
6868         } else if (buf[0] == '2') {
6869                 g_warning("Couldn't write to file\n");
6870         } else if (buf[0] == '3') {
6871                 g_warning("Pipe read failed\n");
6872         }
6873
6874         compose_set_ext_editor_sensitive(compose, TRUE);
6875
6876         g_free(compose->exteditor_file);
6877         compose->exteditor_file    = NULL;
6878         compose->exteditor_pid     = -1;
6879         compose->exteditor_ch      = NULL;
6880         compose->exteditor_tag     = -1;
6881
6882         return FALSE;
6883 }
6884
6885 static void compose_set_ext_editor_sensitive(Compose *compose,
6886                                              gboolean sensitive)
6887 {
6888         GtkItemFactory *ifactory;
6889
6890         ifactory = gtk_item_factory_from_widget(compose->menubar);
6891
6892         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
6893         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
6894         menu_set_sensitive(ifactory, "/Message/Insert file", sensitive);
6895         menu_set_sensitive(ifactory, "/Message/Insert signature", sensitive);
6896         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
6897         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
6898         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
6899                            sensitive);
6900
6901         gtk_widget_set_sensitive(compose->text,                       sensitive);
6902         if (compose->toolbar->send_btn)
6903                 gtk_widget_set_sensitive(compose->toolbar->send_btn,      sensitive);
6904         if (compose->toolbar->sendl_btn)
6905                 gtk_widget_set_sensitive(compose->toolbar->sendl_btn,     sensitive);
6906         if (compose->toolbar->draft_btn)
6907                 gtk_widget_set_sensitive(compose->toolbar->draft_btn,     sensitive);
6908         if (compose->toolbar->insert_btn)
6909                 gtk_widget_set_sensitive(compose->toolbar->insert_btn,    sensitive);
6910         if (compose->toolbar->sig_btn)
6911                 gtk_widget_set_sensitive(compose->toolbar->sig_btn,       sensitive);
6912         if (compose->toolbar->exteditor_btn)
6913                 gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, sensitive);
6914         if (compose->toolbar->linewrap_current_btn)
6915                 gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, sensitive);
6916         if (compose->toolbar->linewrap_all_btn)
6917                 gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, sensitive);
6918 }
6919 #endif /* G_OS_UNIX */
6920
6921 /**
6922  * compose_undo_state_changed:
6923  *
6924  * Change the sensivity of the menuentries undo and redo
6925  **/
6926 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
6927                                        gint redo_state, gpointer data)
6928 {
6929         GtkWidget *widget = GTK_WIDGET(data);
6930         GtkItemFactory *ifactory;
6931
6932         g_return_if_fail(widget != NULL);
6933
6934         ifactory = gtk_item_factory_from_widget(widget);
6935
6936         switch (undo_state) {
6937         case UNDO_STATE_TRUE:
6938                 if (!undostruct->undo_state) {
6939                         undostruct->undo_state = TRUE;
6940                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
6941                 }
6942                 break;
6943         case UNDO_STATE_FALSE:
6944                 if (undostruct->undo_state) {
6945                         undostruct->undo_state = FALSE;
6946                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
6947                 }
6948                 break;
6949         case UNDO_STATE_UNCHANGED:
6950                 break;
6951         case UNDO_STATE_REFRESH:
6952                 menu_set_sensitive(ifactory, "/Edit/Undo",
6953                                    undostruct->undo_state);
6954                 break;
6955         default:
6956                 g_warning("Undo state not recognized");
6957                 break;
6958         }
6959
6960         switch (redo_state) {
6961         case UNDO_STATE_TRUE:
6962                 if (!undostruct->redo_state) {
6963                         undostruct->redo_state = TRUE;
6964                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
6965                 }
6966                 break;
6967         case UNDO_STATE_FALSE:
6968                 if (undostruct->redo_state) {
6969                         undostruct->redo_state = FALSE;
6970                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
6971                 }
6972                 break;
6973         case UNDO_STATE_UNCHANGED:
6974                 break;
6975         case UNDO_STATE_REFRESH:
6976                 menu_set_sensitive(ifactory, "/Edit/Redo",
6977                                    undostruct->redo_state);
6978                 break;
6979         default:
6980                 g_warning("Redo state not recognized");
6981                 break;
6982         }
6983 }
6984
6985 /* callback functions */
6986
6987 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
6988  * includes "non-client" (windows-izm) in calculation, so this calculation
6989  * may not be accurate.
6990  */
6991 static gboolean compose_edit_size_alloc(GtkEditable *widget,
6992                                         GtkAllocation *allocation,
6993                                         GtkSHRuler *shruler)
6994 {
6995         if (prefs_common.show_ruler) {
6996                 gint char_width = 0, char_height = 0;
6997                 gint line_width_in_chars;
6998
6999                 gtkut_get_font_size(GTK_WIDGET(widget),
7000                                     &char_width, &char_height);
7001                 line_width_in_chars =
7002                         (allocation->width - allocation->x) / char_width;
7003
7004                 /* got the maximum */
7005                 gtk_ruler_set_range(GTK_RULER(shruler),
7006                                     0.0, line_width_in_chars, 0,
7007                                     /*line_width_in_chars*/ char_width);
7008         }
7009
7010         return TRUE;
7011 }
7012
7013 static void account_activated(GtkMenuItem *menuitem, gpointer data)
7014 {
7015         Compose *compose = (Compose *)data;
7016
7017         PrefsAccount *ac;
7018         gchar *folderidentifier;
7019
7020         ac = account_find_from_id(
7021                 GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menuitem), MENU_VAL_ID)));
7022         g_return_if_fail(ac != NULL);
7023
7024         if (ac != compose->account)
7025                 compose_select_account(compose, ac, FALSE);
7026
7027         /* Set message save folder */
7028         if (account_get_special_folder(compose->account, F_OUTBOX)) {
7029                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
7030         }
7031         g_signal_connect(G_OBJECT(compose->savemsg_checkbtn), "toggled",
7032                          G_CALLBACK(compose_savemsg_checkbtn_cb), compose);
7033                            
7034         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
7035         if (account_get_special_folder(compose->account, F_OUTBOX)) {
7036                 folderidentifier = folder_item_get_identifier(account_get_special_folder
7037                                   (compose->account, F_OUTBOX));
7038                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
7039                 g_free(folderidentifier);
7040         }
7041 }
7042
7043 static void attach_selected(GtkTreeView *tree_view, GtkTreePath *tree_path,
7044                             GtkTreeViewColumn *column, Compose *compose)
7045 {
7046         compose_attach_property(compose);
7047 }
7048
7049 static gboolean attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
7050                                       gpointer data)
7051 {
7052         Compose *compose = (Compose *)data;
7053         GtkTreeSelection *attach_selection;
7054         gint attach_nr_selected;
7055         GtkItemFactory *ifactory;
7056         
7057         if (!event) return FALSE;
7058
7059         if (event->button == 3) {
7060                 attach_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget));
7061                 attach_nr_selected = gtk_tree_selection_count_selected_rows(attach_selection);
7062                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
7063                         
7064                 if (attach_nr_selected > 0)
7065                 {
7066                         menu_set_sensitive(ifactory, "/Remove", TRUE);
7067                         menu_set_sensitive(ifactory, "/Properties...", TRUE);
7068                 } else {
7069                         menu_set_sensitive(ifactory, "/Remove", FALSE);
7070                         menu_set_sensitive(ifactory, "/Properties...", FALSE);
7071                 }
7072                         
7073                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
7074                                NULL, NULL, event->button, event->time);
7075                 return TRUE;                           
7076         }
7077
7078         return FALSE;
7079 }
7080
7081 static gboolean attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
7082                                    gpointer data)
7083 {
7084         Compose *compose = (Compose *)data;
7085
7086         if (!event) return FALSE;
7087
7088         switch (event->keyval) {
7089         case GDK_Delete:
7090                 compose_attach_remove_selected(compose);
7091                 break;
7092         }
7093         return FALSE;
7094 }
7095
7096 static void compose_allow_user_actions (Compose *compose, gboolean allow)
7097 {
7098         GtkItemFactory *ifactory = gtk_item_factory_from_widget(compose->menubar);
7099         toolbar_comp_set_sensitive(compose, allow);
7100         menu_set_sensitive(ifactory, "/Message", allow);
7101         menu_set_sensitive(ifactory, "/Edit", allow);
7102 #if USE_ASPELL
7103         menu_set_sensitive(ifactory, "/Spelling", allow);
7104 #endif  
7105         menu_set_sensitive(ifactory, "/Options", allow);
7106         menu_set_sensitive(ifactory, "/Tools", allow);
7107         menu_set_sensitive(ifactory, "/Help", allow);
7108         
7109         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), allow);
7110
7111 }
7112
7113 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
7114 {
7115         Compose *compose = (Compose *)data;
7116         
7117         if (prefs_common.work_offline && !inc_offline_should_override())
7118                 return;
7119         
7120         if (compose->draft_timeout_tag != -1) { /* CLAWS: disable draft timeout */
7121                 gtk_timeout_remove(compose->draft_timeout_tag);
7122                 compose->draft_timeout_tag = -1;
7123         }
7124
7125         compose_send(compose);
7126 }
7127
7128 static void compose_send_later_cb(gpointer data, guint action,
7129                                   GtkWidget *widget)
7130 {
7131         Compose *compose = (Compose *)data;
7132         gint val;
7133
7134         val = compose_queue_sub(compose, NULL, NULL, NULL, TRUE);
7135         if (!val) 
7136                 compose_close(compose);
7137         else if (val == -2) {
7138                 alertpanel_error(_("Could not queue message:\n\n%s."), strerror(errno));
7139         }
7140 }
7141
7142 void compose_draft (gpointer data) 
7143 {
7144         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);     
7145 }
7146
7147 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
7148 {
7149         Compose *compose = (Compose *)data;
7150         FolderItem *draft;
7151         gchar *tmp;
7152         gint msgnum;
7153         MsgFlags flag = {0, 0};
7154         static gboolean lock = FALSE;
7155         MsgInfo *newmsginfo;
7156         FILE *fp;
7157         gboolean target_locked = FALSE;
7158         
7159         if (lock) return;
7160
7161         draft = account_get_special_folder(compose->account, F_DRAFT);
7162         g_return_if_fail(draft != NULL);
7163         
7164         if (!g_mutex_trylock(compose->mutex)) {
7165                 /* we don't want to lock the mutex once it's available,
7166                  * because as the only other part of compose.c locking
7167                  * it is compose_close - which means once unlocked,
7168                  * the compose struct will be freed */
7169                 debug_print("couldn't lock mutex, probably sending\n");
7170                 return;
7171         }
7172         
7173         lock = TRUE;
7174
7175         tmp = g_strdup_printf("%s%cdraft.%p", get_tmp_dir(),
7176                               G_DIR_SEPARATOR, compose);
7177         if ((fp = g_fopen(tmp, "wb")) == NULL) {
7178                 FILE_OP_ERROR(tmp, "fopen");
7179                 goto unlock;
7180         }
7181
7182         /* chmod for security */
7183         if (change_file_mode_rw(fp, tmp) < 0) {
7184                 FILE_OP_ERROR(tmp, "chmod");
7185                 g_warning("can't change file mode\n");
7186         }
7187
7188         /* Save draft infos */
7189         fprintf(fp, "X-Sylpheed-Account-Id:%d\n", compose->account->account_id);
7190         fprintf(fp, "S:%s\n", compose->account->address);
7191         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
7192                 gchar *savefolderid;
7193
7194                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
7195                 fprintf(fp, "SCF:%s\n", savefolderid);
7196                 g_free(savefolderid);
7197         }
7198         if (compose->return_receipt) {
7199                 fprintf(fp, "RRCPT:1\n");
7200         }
7201         if (compose->privacy_system) {
7202                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
7203                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
7204                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
7205         }
7206         fprintf(fp, "\n");
7207
7208         if (compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_STORE) < 0) {
7209                 fclose(fp);
7210                 g_unlink(tmp);
7211                 g_free(tmp);
7212                 goto unlock;
7213         }
7214         fclose(fp);
7215         
7216         if (compose->targetinfo) {
7217                 target_locked = MSG_IS_LOCKED(compose->targetinfo->flags);
7218                 flag.perm_flags = target_locked?MSG_LOCKED:0;
7219         }
7220         flag.tmp_flags = MSG_DRAFT;
7221
7222         folder_item_scan(draft);
7223         if ((msgnum = folder_item_add_msg(draft, tmp, &flag, TRUE)) < 0) {
7224                 g_unlink(tmp);
7225                 g_free(tmp);
7226                 if (action != COMPOSE_AUTO_SAVE)
7227                         alertpanel_error(_("Could not save draft."));
7228                 goto unlock;
7229         }
7230         g_free(tmp);
7231         draft->mtime = 0;       /* force updating */
7232
7233         if (compose->mode == COMPOSE_REEDIT) {
7234                 compose_remove_reedit_target(compose, TRUE);
7235         }
7236
7237         newmsginfo = folder_item_get_msginfo(draft, msgnum);
7238         if (newmsginfo) {
7239                 procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
7240                 if (target_locked)
7241                         procmsg_msginfo_set_flags(newmsginfo, MSG_LOCKED, MSG_DRAFT);
7242                 else
7243                         procmsg_msginfo_set_flags(newmsginfo, 0, MSG_DRAFT);
7244                 if (compose_use_attach(compose))
7245                         procmsg_msginfo_set_flags(newmsginfo, 0,
7246                                                   MSG_HAS_ATTACHMENT);
7247
7248                 procmsg_msginfo_free(newmsginfo);
7249         }
7250         
7251         folder_item_scan(draft);
7252         
7253         if (action == COMPOSE_QUIT_EDITING) {
7254                 lock = FALSE;
7255                 g_mutex_unlock(compose->mutex); /* must be done before closing */
7256                 compose_close(compose);
7257                 return;
7258         } else {
7259                 struct stat s;
7260                 gchar *path;
7261
7262                 path = folder_item_fetch_msg(draft, msgnum);
7263                 if (path == NULL) {
7264                         debug_print("can't fetch %s:%d\n",draft->path, msgnum);
7265                         goto unlock;
7266                 }
7267                 if (g_stat(path, &s) < 0) {
7268                         FILE_OP_ERROR(path, "stat");
7269                         g_free(path);
7270                         goto unlock;
7271                 }
7272                 g_free(path);
7273
7274                 procmsg_msginfo_free(compose->targetinfo);
7275                 compose->targetinfo = procmsg_msginfo_new();
7276                 compose->targetinfo->msgnum = msgnum;
7277                 compose->targetinfo->size = s.st_size;
7278                 compose->targetinfo->mtime = s.st_mtime;
7279                 compose->targetinfo->folder = draft;
7280                 if (target_locked)
7281                         procmsg_msginfo_set_flags(compose->targetinfo, MSG_LOCKED, 0);
7282                 compose->mode = COMPOSE_REEDIT;
7283                 
7284                 if (action == COMPOSE_AUTO_SAVE) {
7285                         compose->autosaved_draft = compose->targetinfo;
7286                 }
7287                 compose->modified = FALSE;
7288                 compose_set_title(compose);
7289         }
7290 unlock:
7291         lock = FALSE;
7292         g_mutex_unlock(compose->mutex);
7293 }
7294
7295 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
7296 {
7297         Compose *compose = (Compose *)data;
7298         GList *file_list;
7299
7300         if (compose->redirect_filename != NULL)
7301                 return;
7302
7303         file_list = filesel_select_multiple_files_open(_("Select file"));
7304
7305         if (file_list) {
7306                 GList *tmp;
7307
7308                 for ( tmp = file_list; tmp; tmp = tmp->next) {
7309                         gchar *file = (gchar *) tmp->data;
7310                         gchar *utf8_filename = conv_filename_to_utf8(file);
7311                         compose_attach_append(compose, file, utf8_filename, NULL);
7312                         compose_changed_cb(NULL, compose);
7313                         g_free(file);
7314                         g_free(utf8_filename);
7315                 }
7316                 g_list_free(file_list);
7317         }               
7318 }
7319
7320 static void compose_insert_file_cb(gpointer data, guint action,
7321                                    GtkWidget *widget)
7322 {
7323         Compose *compose = (Compose *)data;
7324         GList *file_list;
7325
7326         file_list = filesel_select_multiple_files_open(_("Select file"));
7327
7328         if (file_list) {
7329                 GList *tmp;
7330
7331                 for ( tmp = file_list; tmp; tmp = tmp->next) {
7332                         gchar *file = (gchar *) tmp->data;
7333                         gchar *filedup = g_strdup(file);
7334                         gchar *shortfile = g_path_get_basename(filedup);
7335                         ComposeInsertResult res;
7336
7337                         res = compose_insert_file(compose, file);
7338                         if (res == COMPOSE_INSERT_READ_ERROR) {
7339                                 alertpanel_error(_("File '%s' could not be read."), shortfile);
7340                         } else if (res == COMPOSE_INSERT_INVALID_CHARACTER) {
7341                                 alertpanel_error(_("File '%s' contained invalid characters\n"
7342                                                    "for the current encoding, insertion may be incorrect."), shortfile);
7343                         }
7344                         g_free(shortfile);
7345                         g_free(filedup);
7346                         g_free(file);
7347                 }
7348                 g_list_free(file_list);
7349         }
7350 }
7351
7352 static void compose_insert_sig_cb(gpointer data, guint action,
7353                                   GtkWidget *widget)
7354 {
7355         Compose *compose = (Compose *)data;
7356
7357         compose_insert_sig(compose, FALSE);
7358 }
7359
7360 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
7361                               gpointer data)
7362 {
7363         gint x, y;
7364         Compose *compose = (Compose *)data;
7365
7366         gtkut_widget_get_uposition(widget, &x, &y);
7367         prefs_common.compose_x = x;
7368         prefs_common.compose_y = y;
7369
7370         if (compose->sending)
7371                 return TRUE;
7372         compose_close_cb(compose, 0, NULL);
7373         return TRUE;
7374 }
7375
7376 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
7377 {
7378         Compose *compose = (Compose *)data;
7379         AlertValue val;
7380
7381 #ifdef G_OS_UNIX
7382         if (compose->exteditor_tag != -1) {
7383                 if (!compose_ext_editor_kill(compose))
7384                         return;
7385         }
7386 #endif
7387
7388         if (compose->modified) {
7389                 val = alertpanel(_("Discard message"),
7390                                  _("This message has been modified. Discard it?"),
7391                                  _("_Discard"), _("_Save to Drafts"), GTK_STOCK_CANCEL);
7392
7393                 switch (val) {
7394                 case G_ALERTDEFAULT:
7395                         if (prefs_common.autosave)
7396                                 compose_remove_draft(compose);                  
7397                         break;
7398                 case G_ALERTALTERNATE:
7399                         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);
7400                         return;
7401                 default:
7402                         return;
7403                 }
7404         }
7405
7406         compose_close(compose);
7407 }
7408
7409 static void compose_set_encoding_cb(gpointer data, guint action,
7410                                     GtkWidget *widget)
7411 {
7412         Compose *compose = (Compose *)data;
7413
7414         if (GTK_CHECK_MENU_ITEM(widget)->active)
7415                 compose->out_encoding = (CharSet)action;
7416 }
7417
7418 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
7419 {
7420         Compose *compose = (Compose *)data;
7421
7422         addressbook_open(compose);
7423 }
7424
7425 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
7426 {
7427         Compose *compose = (Compose *)data;
7428         Template *tmpl;
7429         gchar *msg;
7430         AlertValue val;
7431
7432         tmpl = g_object_get_data(G_OBJECT(widget), "template");
7433         g_return_if_fail(tmpl != NULL);
7434
7435         msg = g_strdup_printf(_("Do you want to apply the template '%s' ?"),
7436                               tmpl->name);
7437         val = alertpanel(_("Apply template"), msg,
7438                          _("_Replace"), _("_Insert"), GTK_STOCK_CANCEL);
7439         g_free(msg);
7440
7441         if (val == G_ALERTDEFAULT)
7442                 compose_template_apply(compose, tmpl, TRUE);
7443         else if (val == G_ALERTALTERNATE)
7444                 compose_template_apply(compose, tmpl, FALSE);
7445 }
7446
7447 static void compose_ext_editor_cb(gpointer data, guint action,
7448                                   GtkWidget *widget)
7449 {
7450         Compose *compose = (Compose *)data;
7451
7452         compose_exec_ext_editor(compose);
7453 }
7454
7455 static void compose_undo_cb(Compose *compose)
7456 {
7457         gboolean prev_autowrap = compose->autowrap;
7458
7459         compose->autowrap = FALSE;
7460         undo_undo(compose->undostruct);
7461         compose->autowrap = prev_autowrap;
7462 }
7463
7464 static void compose_redo_cb(Compose *compose)
7465 {
7466         gboolean prev_autowrap = compose->autowrap;
7467         
7468         compose->autowrap = FALSE;
7469         undo_redo(compose->undostruct);
7470         compose->autowrap = prev_autowrap;
7471 }
7472
7473 static void entry_cut_clipboard(GtkWidget *entry)
7474 {
7475         if (GTK_IS_EDITABLE(entry))
7476                 gtk_editable_cut_clipboard (GTK_EDITABLE(entry));
7477         else if (GTK_IS_TEXT_VIEW(entry))
7478                 gtk_text_buffer_cut_clipboard(
7479                         gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry)),
7480                         gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),
7481                         TRUE);
7482 }
7483
7484 static void entry_copy_clipboard(GtkWidget *entry)
7485 {
7486         if (GTK_IS_EDITABLE(entry))
7487                 gtk_editable_copy_clipboard (GTK_EDITABLE(entry));
7488         else if (GTK_IS_TEXT_VIEW(entry))
7489                 gtk_text_buffer_copy_clipboard(
7490                         gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry)),
7491                         gtk_clipboard_get(GDK_SELECTION_CLIPBOARD));
7492 }
7493
7494 static void entry_paste_clipboard(Compose *compose, GtkWidget *entry, 
7495                                   gboolean wrap, GdkAtom clip)
7496 {
7497         if (GTK_IS_TEXT_VIEW(entry)) {
7498                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry));
7499                 GtkTextMark *mark_start = gtk_text_buffer_get_insert(buffer);
7500                 GtkTextIter start_iter, end_iter;
7501                 gint start, end;
7502                 
7503                 gchar *contents = gtk_clipboard_wait_for_text(gtk_clipboard_get(clip));
7504
7505                 if (contents == NULL)
7506                         return;
7507
7508                 gtk_text_buffer_delete_selection(buffer, FALSE, TRUE);
7509                 gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark_start);
7510                 
7511                 start = gtk_text_iter_get_offset(&start_iter);
7512
7513                 gtk_text_buffer_insert(buffer, &start_iter, contents, strlen(contents));
7514                 
7515                 if (!wrap) {
7516                         end = start + strlen(contents);
7517                         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start);
7518                         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end);
7519                         gtk_text_buffer_apply_tag_by_name(buffer, "no_wrap", &start_iter, &end_iter);
7520                 } else if (wrap && clip == GDK_SELECTION_PRIMARY) {
7521                         mark_start = gtk_text_buffer_get_insert(buffer);
7522                         gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark_start);
7523                         gtk_text_iter_backward_char(&start_iter);
7524                         compose_beautify_paragraph(compose, &start_iter, TRUE);
7525                 }
7526                 
7527         } else if (GTK_IS_EDITABLE(entry))
7528                 gtk_editable_paste_clipboard (GTK_EDITABLE(entry));
7529         
7530 }
7531
7532 static void entry_allsel(GtkWidget *entry)
7533 {
7534         if (GTK_IS_EDITABLE(entry))
7535                 gtk_editable_select_region(GTK_EDITABLE(entry), 0, -1);
7536         else if (GTK_IS_TEXT_VIEW(entry)) {
7537                 GtkTextIter startiter, enditer;
7538                 GtkTextBuffer *textbuf;
7539
7540                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry));
7541                 gtk_text_buffer_get_start_iter(textbuf, &startiter);
7542                 gtk_text_buffer_get_end_iter(textbuf, &enditer);
7543
7544                 gtk_text_buffer_move_mark_by_name(textbuf, 
7545                         "selection_bound", &startiter);
7546                 gtk_text_buffer_move_mark_by_name(textbuf, 
7547                         "insert", &enditer);
7548         }
7549 }
7550
7551 static void compose_cut_cb(Compose *compose)
7552 {
7553         if (compose->focused_editable &&
7554             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7555                 entry_cut_clipboard(compose->focused_editable);
7556 }
7557
7558 static void compose_copy_cb(Compose *compose)
7559 {
7560         if (compose->focused_editable &&
7561             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7562                 entry_copy_clipboard(compose->focused_editable);
7563 }
7564
7565 static void compose_paste_cb(Compose *compose)
7566 {
7567         gint prev_autowrap;
7568         GtkTextBuffer *buffer;
7569         BLOCK_WRAP();
7570         if (compose->focused_editable &&
7571             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7572                 entry_paste_clipboard(compose, compose->focused_editable, 
7573                                 prefs_common.linewrap_pastes,
7574                                 GDK_SELECTION_CLIPBOARD);
7575         UNBLOCK_WRAP();
7576 }
7577
7578 static void compose_paste_as_quote_cb(Compose *compose)
7579 {
7580         gint wrap_quote = prefs_common.linewrap_quote;
7581         if (compose->focused_editable &&
7582             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
7583                 /* let text_insert() (called directly or at a later time
7584                  * after the gtk_editable_paste_clipboard) know that 
7585                  * text is to be inserted as a quotation. implemented
7586                  * by using a simple refcount... */
7587                 gint paste_as_quotation = GPOINTER_TO_INT(g_object_get_data(
7588                                                 G_OBJECT(compose->focused_editable),
7589                                                 "paste_as_quotation"));
7590                 g_object_set_data(G_OBJECT(compose->focused_editable),
7591                                     "paste_as_quotation",
7592                                     GINT_TO_POINTER(paste_as_quotation + 1));
7593                 prefs_common.linewrap_quote = prefs_common.linewrap_pastes;
7594                 entry_paste_clipboard(compose, compose->focused_editable, 
7595                                 prefs_common.linewrap_pastes,
7596                                 GDK_SELECTION_CLIPBOARD);
7597                 prefs_common.linewrap_quote = wrap_quote;
7598         }
7599 }
7600
7601 static void compose_paste_no_wrap_cb(Compose *compose)
7602 {
7603         gint prev_autowrap;
7604         GtkTextBuffer *buffer;
7605         BLOCK_WRAP();
7606         if (compose->focused_editable &&
7607             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7608                 entry_paste_clipboard(compose, compose->focused_editable, FALSE,
7609                         GDK_SELECTION_CLIPBOARD);
7610         UNBLOCK_WRAP();
7611 }
7612
7613 static void compose_paste_wrap_cb(Compose *compose)
7614 {
7615         gint prev_autowrap;
7616         GtkTextBuffer *buffer;
7617         BLOCK_WRAP();
7618         if (compose->focused_editable &&
7619             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7620                 entry_paste_clipboard(compose, compose->focused_editable, TRUE,
7621                         GDK_SELECTION_CLIPBOARD);
7622         UNBLOCK_WRAP();
7623 }
7624
7625 static void compose_allsel_cb(Compose *compose)
7626 {
7627         if (compose->focused_editable &&
7628             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7629                 entry_allsel(compose->focused_editable);
7630 }
7631
7632 static void textview_move_beginning_of_line (GtkTextView *text)
7633 {
7634         GtkTextBuffer *buffer;
7635         GtkTextMark *mark;
7636         GtkTextIter ins;
7637
7638         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7639
7640         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7641         mark = gtk_text_buffer_get_insert(buffer);
7642         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7643         gtk_text_iter_set_line_offset(&ins, 0);
7644         gtk_text_buffer_place_cursor(buffer, &ins);
7645 }
7646
7647 static void textview_move_forward_character (GtkTextView *text)
7648 {
7649         GtkTextBuffer *buffer;
7650         GtkTextMark *mark;
7651         GtkTextIter ins;
7652
7653         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7654
7655         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7656         mark = gtk_text_buffer_get_insert(buffer);
7657         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7658         if (gtk_text_iter_forward_cursor_position(&ins))
7659                 gtk_text_buffer_place_cursor(buffer, &ins);
7660 }
7661
7662 static void textview_move_backward_character (GtkTextView *text)
7663 {
7664         GtkTextBuffer *buffer;
7665         GtkTextMark *mark;
7666         GtkTextIter ins;
7667
7668         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7669
7670         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7671         mark = gtk_text_buffer_get_insert(buffer);
7672         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7673         if (gtk_text_iter_backward_cursor_position(&ins))
7674                 gtk_text_buffer_place_cursor(buffer, &ins);
7675 }
7676
7677 static void textview_move_forward_word (GtkTextView *text)
7678 {
7679         GtkTextBuffer *buffer;
7680         GtkTextMark *mark;
7681         GtkTextIter ins;
7682         gint count;
7683
7684         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7685
7686         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7687         mark = gtk_text_buffer_get_insert(buffer);
7688         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7689         count = gtk_text_iter_inside_word (&ins) ? 2 : 1;
7690         if (gtk_text_iter_forward_word_ends(&ins, count)) {
7691                 gtk_text_iter_backward_word_start(&ins);
7692                 gtk_text_buffer_place_cursor(buffer, &ins);
7693         }
7694 }
7695
7696 static void textview_move_backward_word (GtkTextView *text)
7697 {
7698         GtkTextBuffer *buffer;
7699         GtkTextMark *mark;
7700         GtkTextIter ins;
7701         gint count;
7702
7703         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7704
7705         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7706         mark = gtk_text_buffer_get_insert(buffer);
7707         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7708         count = gtk_text_iter_inside_word (&ins) ? 2 : 1;
7709         if (gtk_text_iter_backward_word_starts(&ins, 1))
7710                 gtk_text_buffer_place_cursor(buffer, &ins);
7711 }
7712
7713 static void textview_move_end_of_line (GtkTextView *text)
7714 {
7715         GtkTextBuffer *buffer;
7716         GtkTextMark *mark;
7717         GtkTextIter ins;
7718
7719         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7720
7721         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7722         mark = gtk_text_buffer_get_insert(buffer);
7723         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7724         if (gtk_text_iter_forward_to_line_end(&ins))
7725                 gtk_text_buffer_place_cursor(buffer, &ins);
7726 }
7727
7728 static void textview_move_next_line (GtkTextView *text)
7729 {
7730         GtkTextBuffer *buffer;
7731         GtkTextMark *mark;
7732         GtkTextIter ins;
7733         gint offset;
7734
7735         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7736
7737         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7738         mark = gtk_text_buffer_get_insert(buffer);
7739         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7740         offset = gtk_text_iter_get_line_offset(&ins);
7741         if (gtk_text_iter_forward_line(&ins)) {
7742                 gtk_text_iter_set_line_offset(&ins, offset);
7743                 gtk_text_buffer_place_cursor(buffer, &ins);
7744         }
7745 }
7746
7747 static void textview_move_previous_line (GtkTextView *text)
7748 {
7749         GtkTextBuffer *buffer;
7750         GtkTextMark *mark;
7751         GtkTextIter ins;
7752         gint offset;
7753
7754         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7755
7756         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7757         mark = gtk_text_buffer_get_insert(buffer);
7758         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7759         offset = gtk_text_iter_get_line_offset(&ins);
7760         if (gtk_text_iter_backward_line(&ins)) {
7761                 gtk_text_iter_set_line_offset(&ins, offset);
7762                 gtk_text_buffer_place_cursor(buffer, &ins);
7763         }
7764 }
7765
7766 static void textview_delete_forward_character (GtkTextView *text)
7767 {
7768         GtkTextBuffer *buffer;
7769         GtkTextMark *mark;
7770         GtkTextIter ins, end_iter;
7771
7772         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7773
7774         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7775         mark = gtk_text_buffer_get_insert(buffer);
7776         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7777         end_iter = ins;
7778         if (gtk_text_iter_forward_char(&end_iter)) {
7779                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7780         }
7781 }
7782
7783 static void textview_delete_backward_character (GtkTextView *text)
7784 {
7785         GtkTextBuffer *buffer;
7786         GtkTextMark *mark;
7787         GtkTextIter ins, end_iter;
7788
7789         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7790
7791         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7792         mark = gtk_text_buffer_get_insert(buffer);
7793         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7794         end_iter = ins;
7795         if (gtk_text_iter_backward_char(&end_iter)) {
7796                 gtk_text_buffer_delete(buffer, &end_iter, &ins);
7797         }
7798 }
7799
7800 static void textview_delete_forward_word (GtkTextView *text)
7801 {
7802         GtkTextBuffer *buffer;
7803         GtkTextMark *mark;
7804         GtkTextIter ins, end_iter;
7805
7806         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7807
7808         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7809         mark = gtk_text_buffer_get_insert(buffer);
7810         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7811         end_iter = ins;
7812         if (gtk_text_iter_forward_word_end(&end_iter)) {
7813                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7814         }
7815 }
7816
7817 static void textview_delete_backward_word (GtkTextView *text)
7818 {
7819         GtkTextBuffer *buffer;
7820         GtkTextMark *mark;
7821         GtkTextIter ins, end_iter;
7822
7823         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7824
7825         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7826         mark = gtk_text_buffer_get_insert(buffer);
7827         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7828         end_iter = ins;
7829         if (gtk_text_iter_backward_word_start(&end_iter)) {
7830                 gtk_text_buffer_delete(buffer, &end_iter, &ins);
7831         }
7832 }
7833
7834 static void textview_delete_line (GtkTextView *text)
7835 {
7836         GtkTextBuffer *buffer;
7837         GtkTextMark *mark;
7838         GtkTextIter ins, start_iter, end_iter;
7839         gboolean found;
7840
7841         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7842
7843         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7844         mark = gtk_text_buffer_get_insert(buffer);
7845         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7846
7847         start_iter = ins;
7848         gtk_text_iter_set_line_offset(&start_iter, 0);
7849
7850         end_iter = ins;
7851         if (gtk_text_iter_ends_line(&end_iter))
7852                 found = gtk_text_iter_forward_char(&end_iter);
7853         else
7854                 found = gtk_text_iter_forward_to_line_end(&end_iter);
7855
7856         if (found)
7857                 gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
7858 }
7859
7860 static void textview_delete_to_line_end (GtkTextView *text)
7861 {
7862         GtkTextBuffer *buffer;
7863         GtkTextMark *mark;
7864         GtkTextIter ins, end_iter;
7865         gboolean found;
7866
7867         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7868
7869         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7870         mark = gtk_text_buffer_get_insert(buffer);
7871         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7872         end_iter = ins;
7873         if (gtk_text_iter_ends_line(&end_iter))
7874                 found = gtk_text_iter_forward_char(&end_iter);
7875         else
7876                 found = gtk_text_iter_forward_to_line_end(&end_iter);
7877         if (found)
7878                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7879 }
7880
7881 static void compose_advanced_action_cb(Compose *compose,
7882                                         ComposeCallAdvancedAction action)
7883 {
7884         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
7885         static struct {
7886                 void (*do_action) (GtkTextView *text);
7887         } action_table[] = {
7888                 {textview_move_beginning_of_line},
7889                 {textview_move_forward_character},
7890                 {textview_move_backward_character},
7891                 {textview_move_forward_word},
7892                 {textview_move_backward_word},
7893                 {textview_move_end_of_line},
7894                 {textview_move_next_line},
7895                 {textview_move_previous_line},
7896                 {textview_delete_forward_character},
7897                 {textview_delete_backward_character},
7898                 {textview_delete_forward_word},
7899                 {textview_delete_backward_word},
7900                 {textview_delete_line},
7901                 {NULL}, /* gtk_stext_delete_line_n */
7902                 {textview_delete_to_line_end}
7903         };
7904
7905         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
7906
7907         if (action >= COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE &&
7908             action <= COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END) {
7909                 if (action_table[action].do_action)
7910                         action_table[action].do_action(text);
7911                 else
7912                         g_warning("Not implemented yet.");
7913         }
7914 }
7915
7916 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
7917 {
7918         gchar *str = NULL;
7919         
7920         if (GTK_IS_EDITABLE(widget)) {
7921                 str = gtk_editable_get_chars(GTK_EDITABLE(widget), 0, -1);
7922                 gtk_editable_set_position(GTK_EDITABLE(widget), 
7923                         strlen(str));
7924                 g_free(str);
7925                 if (widget->parent && widget->parent->parent
7926                  && widget->parent->parent->parent) {
7927                         if (GTK_IS_SCROLLED_WINDOW(widget->parent->parent->parent)) {
7928                                 gint y = widget->allocation.y;
7929                                 gint height = widget->allocation.height;
7930                                 GtkAdjustment *shown = gtk_scrolled_window_get_vadjustment
7931                                         (GTK_SCROLLED_WINDOW(widget->parent->parent->parent));
7932
7933                                 if (y < (int)shown->value) {
7934                                         gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), y - 1);
7935                                 }
7936                                 if (y + height > (int)shown->value + (int)shown->page_size) {
7937                                         if (y - height - 1 < (int)shown->upper - (int)shown->page_size) {
7938                                                 gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), 
7939                                                         y + height - (int)shown->page_size - 1);
7940                                         } else {
7941                                                 gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), 
7942                                                         (int)shown->upper - (int)shown->page_size - 1);
7943                                         }
7944                                 }
7945                         }
7946                 }
7947         }
7948
7949         if (GTK_IS_EDITABLE(widget) || GTK_IS_TEXT_VIEW(widget))
7950                 compose->focused_editable = widget;
7951 }
7952
7953 static void compose_changed_cb(GtkTextBuffer *textbuf, Compose *compose)
7954 {
7955         compose->modified = TRUE;
7956         compose_set_title(compose);
7957 }
7958
7959 static void compose_wrap_cb(gpointer data, guint action, GtkWidget *widget)
7960 {
7961         Compose *compose = (Compose *)data;
7962
7963         if (action == 1)
7964                 compose_wrap_all_full(compose, TRUE);
7965         else
7966                 compose_beautify_paragraph(compose, NULL, TRUE);
7967 }
7968
7969 static void compose_find_cb(gpointer data, guint action, GtkWidget *widget)
7970 {
7971         Compose *compose = (Compose *)data;
7972
7973         message_search_compose(compose);
7974 }
7975
7976 static void compose_toggle_autowrap_cb(gpointer data, guint action,
7977                                        GtkWidget *widget)
7978 {
7979         Compose *compose = (Compose *)data;
7980         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
7981         if (compose->autowrap)
7982                 compose_wrap_all_full(compose, TRUE);
7983         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
7984 }
7985
7986 static void compose_toggle_sign_cb(gpointer data, guint action,
7987                                    GtkWidget *widget)
7988 {
7989         Compose *compose = (Compose *)data;
7990
7991         if (GTK_CHECK_MENU_ITEM(widget)->active)
7992                 compose->use_signing = TRUE;
7993         else
7994                 compose->use_signing = FALSE;
7995 }
7996
7997 static void compose_toggle_encrypt_cb(gpointer data, guint action,
7998                                       GtkWidget *widget)
7999 {
8000         Compose *compose = (Compose *)data;
8001
8002         if (GTK_CHECK_MENU_ITEM(widget)->active)
8003                 compose->use_encryption = TRUE;
8004         else
8005                 compose->use_encryption = FALSE;
8006 }
8007
8008 static void activate_privacy_system(Compose *compose, PrefsAccount *account, gboolean warn) 
8009 {
8010         g_free(compose->privacy_system);
8011
8012         compose->privacy_system = g_strdup(account->default_privacy_system);
8013         compose_update_privacy_system_menu_item(compose, warn);
8014 }
8015
8016 static void compose_toggle_ruler_cb(gpointer data, guint action,
8017                                     GtkWidget *widget)
8018 {
8019         Compose *compose = (Compose *)data;
8020
8021         if (GTK_CHECK_MENU_ITEM(widget)->active) {
8022                 gtk_widget_show(compose->ruler_hbox);
8023                 prefs_common.show_ruler = TRUE;
8024         } else {
8025                 gtk_widget_hide(compose->ruler_hbox);
8026                 gtk_widget_queue_resize(compose->edit_vbox);
8027                 prefs_common.show_ruler = FALSE;
8028         }
8029 }
8030
8031 static void compose_attach_drag_received_cb (GtkWidget          *widget,
8032                                              GdkDragContext     *context,
8033                                              gint                x,
8034                                              gint                y,
8035                                              GtkSelectionData   *data,
8036                                              guint               info,
8037                                              guint               time,
8038                                              gpointer            user_data)
8039 {
8040         Compose *compose = (Compose *)user_data;
8041         GList *list, *tmp;
8042
8043         if (gdk_atom_name(data->type) && 
8044             !strcmp(gdk_atom_name(data->type), "text/uri-list")
8045             && gtk_drag_get_source_widget(context) != 
8046                 mainwindow_get_mainwindow()->summaryview->ctree) {
8047                 list = uri_list_extract_filenames((const gchar *)data->data);
8048                 for (tmp = list; tmp != NULL; tmp = tmp->next)
8049                         compose_attach_append
8050                                 (compose, (const gchar *)tmp->data,
8051                                  (const gchar *)tmp->data, NULL);
8052                 if (list) compose_changed_cb(NULL, compose);
8053                 list_free_strings(list);
8054                 g_list_free(list);
8055         } else if (gtk_drag_get_source_widget(context) 
8056                    == mainwindow_get_mainwindow()->summaryview->ctree) {
8057                 /* comes from our summaryview */
8058                 SummaryView * summaryview = NULL;
8059                 GSList * list = NULL, *cur = NULL;
8060                 
8061                 if (mainwindow_get_mainwindow())
8062                         summaryview = mainwindow_get_mainwindow()->summaryview;
8063                 
8064                 if (summaryview)
8065                         list = summary_get_selected_msg_list(summaryview);
8066                 
8067                 for (cur = list; cur; cur = cur->next) {
8068                         MsgInfo *msginfo = (MsgInfo *)cur->data;
8069                         gchar *file = NULL;
8070                         if (msginfo)
8071                                 file = procmsg_get_message_file_full(msginfo, 
8072                                         TRUE, TRUE);
8073                         if (file) {
8074                                 compose_attach_append(compose, (const gchar *)file, 
8075                                         (const gchar *)file, "message/rfc822");
8076                                 g_free(file);
8077                         }
8078                 }
8079                 g_slist_free(list);
8080         }
8081 }
8082
8083 static gboolean compose_drag_drop(GtkWidget *widget,
8084                                   GdkDragContext *drag_context,
8085                                   gint x, gint y,
8086                                   guint time, gpointer user_data)
8087 {
8088         /* not handling this signal makes compose_insert_drag_received_cb
8089          * called twice */
8090         return TRUE;                                     
8091 }
8092
8093 static void compose_insert_drag_received_cb (GtkWidget          *widget,
8094                                              GdkDragContext     *drag_context,
8095                                              gint                x,
8096                                              gint                y,
8097                                              GtkSelectionData   *data,
8098                                              guint               info,
8099                                              guint               time,
8100                                              gpointer            user_data)
8101 {
8102         Compose *compose = (Compose *)user_data;
8103         GList *list, *tmp;
8104
8105         /* strangely, testing data->type == gdk_atom_intern("text/uri-list", TRUE)
8106          * does not work */
8107         if (gdk_atom_name(data->type) && !strcmp(gdk_atom_name(data->type), "text/uri-list")) {
8108                 list = uri_list_extract_filenames((const gchar *)data->data);
8109                 for (tmp = list; tmp != NULL; tmp = tmp->next) {
8110                         compose_insert_file(compose, (const gchar *)tmp->data);
8111                 }
8112                 list_free_strings(list);
8113                 g_list_free(list);
8114                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8115                 return;
8116         } else {
8117 #if GTK_CHECK_VERSION(2, 8, 0)
8118                 /* do nothing, handled by GTK */
8119 #else
8120                 gchar *tmpfile = get_tmp_file();
8121                 str_write_to_file((const gchar *)data->data, tmpfile);
8122                 compose_insert_file(compose, tmpfile);
8123                 g_unlink(tmpfile);
8124                 g_free(tmpfile);
8125                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8126 #endif
8127                 return;
8128         }
8129         gtk_drag_finish(drag_context, TRUE, FALSE, time);
8130 }
8131
8132 static void compose_header_drag_received_cb (GtkWidget          *widget,
8133                                              GdkDragContext     *drag_context,
8134                                              gint                x,
8135                                              gint                y,
8136                                              GtkSelectionData   *data,
8137                                              guint               info,
8138                                              guint               time,
8139                                              gpointer            user_data)
8140 {
8141         GtkEditable *entry = (GtkEditable *)user_data;
8142         gchar *email = (gchar *)data->data;
8143
8144         /* strangely, testing data->type == gdk_atom_intern("text/plain", TRUE)
8145          * does not work */
8146
8147         if (!strncmp(email, "mailto:", strlen("mailto:"))) {
8148                 gchar *decoded=g_new(gchar, strlen(email));
8149                 int start = 0;
8150
8151                 email += strlen("mailto:");
8152                 decode_uri(decoded, email); /* will fit */
8153                 gtk_editable_delete_text(entry, 0, -1);
8154                 gtk_editable_insert_text(entry, decoded, strlen(decoded), &start);
8155                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8156                 g_free(decoded);
8157                 return;
8158         }
8159         gtk_drag_finish(drag_context, TRUE, FALSE, time);
8160 }
8161
8162 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
8163                                              GtkWidget *widget)
8164 {
8165         Compose *compose = (Compose *)data;
8166
8167         if (GTK_CHECK_MENU_ITEM(widget)->active)
8168                 compose->return_receipt = TRUE;
8169         else
8170                 compose->return_receipt = FALSE;
8171 }
8172
8173 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
8174                                              GtkWidget *widget)
8175 {
8176         Compose *compose = (Compose *)data;
8177
8178         if (GTK_CHECK_MENU_ITEM(widget)->active)
8179                 compose->remove_references = TRUE;
8180         else
8181                 compose->remove_references = FALSE;
8182 }
8183
8184 gboolean compose_headerentry_key_press_event_cb(GtkWidget *entry,
8185                                             GdkEventKey *event,
8186                                             ComposeHeaderEntry *headerentry)
8187 {
8188         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
8189             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
8190             !(event->state & GDK_MODIFIER_MASK) &&
8191             (event->keyval == GDK_BackSpace) &&
8192             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
8193                 gtk_container_remove
8194                         (GTK_CONTAINER(headerentry->compose->header_table),
8195                          headerentry->combo);
8196                 gtk_container_remove
8197                         (GTK_CONTAINER(headerentry->compose->header_table),
8198                          headerentry->entry);
8199                 headerentry->compose->header_list =
8200                         g_slist_remove(headerentry->compose->header_list,
8201                                        headerentry);
8202                 g_free(headerentry);
8203         } else  if (event->keyval == GDK_Tab) {
8204                 if (headerentry->compose->header_last == headerentry) {
8205                         /* Override default next focus, and give it to subject_entry
8206                          * instead of notebook tabs
8207                          */
8208                         g_signal_stop_emission_by_name(G_OBJECT(entry), "key-press-event"); 
8209                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
8210                         return TRUE;
8211                 }
8212         }
8213         return FALSE;
8214 }
8215
8216 gboolean compose_headerentry_changed_cb(GtkWidget *entry,
8217                                     ComposeHeaderEntry *headerentry)
8218 {
8219         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
8220                 headerentry->compose->header_list =
8221                         g_slist_append(headerentry->compose->header_list,
8222                                        headerentry);
8223                 
8224                 compose_create_header_entry(headerentry->compose);
8225                 g_signal_handlers_disconnect_matched
8226                         (G_OBJECT(entry), G_SIGNAL_MATCH_DATA,
8227                          0, 0, NULL, NULL, headerentry);
8228                 
8229                 /* Automatically scroll down */
8230                 compose_show_first_last_header(headerentry->compose, FALSE);
8231                 
8232         }
8233         return FALSE;
8234 }
8235
8236 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
8237 {
8238         GtkAdjustment *vadj;
8239
8240         g_return_if_fail(compose);
8241         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
8242         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
8243
8244         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
8245         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
8246 }
8247
8248 static void text_inserted(GtkTextBuffer *buffer, GtkTextIter *iter,
8249                           const gchar *text, gint len, Compose *compose)
8250 {
8251         gint paste_as_quotation = GPOINTER_TO_INT(g_object_get_data
8252                                 (G_OBJECT(compose->text), "paste_as_quotation"));
8253         GtkTextMark *mark;
8254
8255         g_return_if_fail(text != NULL);
8256
8257         g_signal_handlers_block_by_func(G_OBJECT(buffer),
8258                                         G_CALLBACK(text_inserted),
8259                                         compose);
8260         if (paste_as_quotation) {
8261                 gchar *new_text;
8262                 gchar *qmark;
8263
8264                 if (len < 0)
8265                         len = strlen(text);
8266
8267                 new_text = g_strndup(text, len);
8268                 if (prefs_common.quotemark && *prefs_common.quotemark)
8269                         qmark = prefs_common.quotemark;
8270                 else
8271                         qmark = "> ";
8272
8273                 mark = gtk_text_buffer_create_mark(buffer, NULL, iter, FALSE);
8274                 gtk_text_buffer_place_cursor(buffer, iter);
8275
8276                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text, TRUE);
8277                 g_free(new_text);
8278                 g_object_set_data(G_OBJECT(compose->text), "paste_as_quotation",
8279                                   GINT_TO_POINTER(paste_as_quotation - 1));
8280                                   
8281                 gtk_text_buffer_get_iter_at_mark(buffer, iter, mark);
8282                 gtk_text_buffer_place_cursor(buffer, iter);
8283         } else {
8284                 if (strcmp(text, "\n") || automatic_break
8285                 || gtk_text_iter_starts_line(iter))
8286                         gtk_text_buffer_insert(buffer, iter, text, len);
8287                 else {
8288                         debug_print("insert nowrap \\n\n");
8289                         gtk_text_buffer_insert_with_tags_by_name(buffer, 
8290                                 iter, text, len, "no_join", NULL);
8291                 }
8292         }
8293         
8294         mark = gtk_text_buffer_create_mark(buffer, NULL, iter, FALSE);
8295         
8296         compose_beautify_paragraph(compose, iter, FALSE);
8297
8298         gtk_text_buffer_get_iter_at_mark(buffer, iter, mark);
8299         gtk_text_buffer_delete_mark(buffer, mark);
8300
8301         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
8302                                           G_CALLBACK(text_inserted),
8303                                           compose);
8304         g_signal_stop_emission_by_name(G_OBJECT(buffer), "insert-text");
8305
8306         if (prefs_common.autosave && 
8307             gtk_text_buffer_get_char_count(buffer) % prefs_common.autosave_length == 0)
8308                 compose->draft_timeout_tag = gtk_timeout_add
8309                         (500, (GtkFunction) compose_defer_auto_save_draft, compose);
8310 }
8311 static gint compose_defer_auto_save_draft(Compose *compose)
8312 {
8313         compose->draft_timeout_tag = -1;
8314         compose_draft_cb((gpointer)compose, COMPOSE_AUTO_SAVE, NULL);
8315         return FALSE;
8316 }
8317
8318 #if USE_ASPELL
8319 static void compose_check_all(Compose *compose)
8320 {
8321         if (compose->gtkaspell)
8322                 gtkaspell_check_all(compose->gtkaspell);
8323 }
8324
8325 static void compose_highlight_all(Compose *compose)
8326 {
8327         if (compose->gtkaspell)
8328                 gtkaspell_highlight_all(compose->gtkaspell);
8329 }
8330
8331 static void compose_check_backwards(Compose *compose)
8332 {
8333         if (compose->gtkaspell) 
8334                 gtkaspell_check_backwards(compose->gtkaspell);
8335         else {
8336                 GtkItemFactory *ifactory;
8337                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
8338                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
8339                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
8340         }
8341 }
8342
8343 static void compose_check_forwards_go(Compose *compose)
8344 {
8345         if (compose->gtkaspell) 
8346                 gtkaspell_check_forwards_go(compose->gtkaspell);
8347         else {
8348                 GtkItemFactory *ifactory;
8349                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
8350                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
8351                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
8352         }
8353 }
8354 #endif
8355
8356 /*!
8357  *\brief        Guess originating forward account from MsgInfo and several 
8358  *              "common preference" settings. Return NULL if no guess. 
8359  */
8360 static PrefsAccount *compose_guess_forward_account_from_msginfo(MsgInfo *msginfo)
8361 {
8362         PrefsAccount *account = NULL;
8363         
8364         g_return_val_if_fail(msginfo, NULL);
8365         g_return_val_if_fail(msginfo->folder, NULL);
8366         g_return_val_if_fail(msginfo->folder->prefs, NULL);
8367
8368         if (msginfo->folder->prefs->enable_default_account)
8369                 account = account_find_from_id(msginfo->folder->prefs->default_account);
8370                 
8371         if (!account) 
8372                 account = msginfo->folder->folder->account;
8373                 
8374         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
8375                 gchar *to;
8376                 Xstrdup_a(to, msginfo->to, return NULL);
8377                 extract_address(to);
8378                 account = account_find_from_address(to);
8379         }
8380
8381         if (!account && prefs_common.forward_account_autosel) {
8382                 gchar cc[BUFFSIZE];
8383                 if (!procheader_get_header_from_msginfo
8384                         (msginfo, cc,sizeof cc , "CC:")) { /* Found a CC header */
8385                         extract_address(cc);
8386                         account = account_find_from_address(cc);
8387                 }
8388         }
8389         
8390         return account;
8391 }
8392
8393 static gboolean compose_close(Compose *compose)
8394 {
8395         gint x, y;
8396
8397         if (!g_mutex_trylock(compose->mutex)) {
8398                 /* we have to wait for the (possibly deferred by auto-save)
8399                  * drafting to be done, before destroying the compose under
8400                  * it. */
8401                 debug_print("waiting for drafting to finish...\n");
8402                 g_timeout_add (500, (GSourceFunc) compose_close, compose);
8403                 return FALSE;
8404         }
8405         g_return_val_if_fail(compose, FALSE);
8406         gtkut_widget_get_uposition(compose->window, &x, &y);
8407         prefs_common.compose_x = x;
8408         prefs_common.compose_y = y;
8409         g_mutex_unlock(compose->mutex);
8410         compose_destroy(compose);
8411         return FALSE;
8412 }
8413
8414 /**
8415  * Add entry field for each address in list.
8416  * \param compose     E-Mail composition object.
8417  * \param listAddress List of (formatted) E-Mail addresses.
8418  */
8419 static void compose_add_field_list( Compose *compose, GList *listAddress ) {
8420         GList *node;
8421         gchar *addr;
8422         node = listAddress;
8423         while( node ) {
8424                 addr = ( gchar * ) node->data;
8425                 compose_entry_append( compose, addr, COMPOSE_TO );
8426                 node = g_list_next( node );
8427         }
8428 }
8429
8430 void compose_reply_from_messageview(MessageView *msgview, GSList *msginfo_list, 
8431                                     guint action)
8432 {
8433         gchar *body;
8434         GSList *new_msglist = NULL;
8435         MsgInfo *tmp_msginfo = NULL;
8436         gboolean originally_enc = FALSE;
8437         Compose *compose = NULL;
8438
8439         g_return_if_fail(msgview != NULL);
8440
8441         g_return_if_fail(msginfo_list != NULL);
8442
8443         if (g_slist_length(msginfo_list) == 1) {
8444                 MimeInfo *mimeinfo = messageview_get_selected_mime_part(msgview);
8445                 MsgInfo *orig_msginfo = (MsgInfo *)msginfo_list->data;
8446                 
8447                 if (mimeinfo != NULL && mimeinfo->type == MIMETYPE_MESSAGE && 
8448                     !g_ascii_strcasecmp(mimeinfo->subtype, "rfc822")) {
8449                         tmp_msginfo = procmsg_msginfo_new_from_mimeinfo(
8450                                                 orig_msginfo, mimeinfo);
8451                         if (tmp_msginfo != NULL) {
8452                                 new_msglist = g_slist_append(NULL, tmp_msginfo);
8453                                 if (procmime_msginfo_is_encrypted(orig_msginfo)) {
8454                                         originally_enc = TRUE;
8455                                 }
8456                         } 
8457                 }
8458         }
8459
8460         body = messageview_get_selection(msgview);
8461
8462         if (new_msglist) {
8463                 compose = compose_reply_mode((ComposeMode)action, new_msglist, body);
8464                 procmsg_msginfo_free(tmp_msginfo);
8465                 g_slist_free(new_msglist);
8466         } else
8467                 compose = compose_reply_mode((ComposeMode)action, msginfo_list, body);
8468
8469         if (originally_enc) {
8470                 compose_force_encryption(compose, compose->account, FALSE);
8471         }
8472
8473         g_free(body);
8474 }
8475
8476 void compose_set_position(Compose *compose, gint pos)
8477 {
8478         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
8479
8480         gtkut_text_view_set_position(text, pos);
8481 }
8482
8483 gboolean compose_search_string(Compose *compose,
8484                                 const gchar *str, gboolean case_sens)
8485 {
8486         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
8487
8488         return gtkut_text_view_search_string(text, str, case_sens);
8489 }
8490
8491 gboolean compose_search_string_backward(Compose *compose,
8492                                 const gchar *str, gboolean case_sens)
8493 {
8494         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
8495
8496         return gtkut_text_view_search_string_backward(text, str, case_sens);
8497 }
8498
8499 /*
8500  * End of Source.
8501  */