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