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