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