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