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