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