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