sync with sylpheed 0.6.4cvs18
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 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 <unistd.h>
57 #include <time.h>
58 /* #include <sys/utsname.h> */
59 #include <stdlib.h>
60 #include <sys/wait.h>
61 #include <signal.h>
62 #include <errno.h>
63
64 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
65 #  include <wchar.h>
66 #  include <wctype.h>
67 #endif
68
69
70 #include "gtkstext.h"
71
72 #include "intl.h"
73 #include "main.h"
74 #include "mainwindow.h"
75 #include "compose.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "send.h"
81 #include "news.h"
82 #include "customheader.h"
83 #include "prefs_common.h"
84 #include "prefs_account.h"
85 #include "account.h"
86 #include "filesel.h"
87 #include "procheader.h"
88 #include "procmime.h"
89 #include "statusbar.h"
90 #include "about.h"
91 #include "base64.h"
92 #include "codeconv.h"
93 #include "utils.h"
94 #include "gtkutils.h"
95 #include "socket.h"
96 #include "alertpanel.h"
97 #include "manage_window.h"
98 #include "gtkshruler.h"
99 #include "folder.h"
100 #include "addr_compl.h"
101 #include "template_select.h"
102 #include "quote_fmt.h"
103 #include "template.h"
104
105 #if USE_GPGME
106 #  include "rfc2015.h"
107 #endif
108
109 typedef enum
110 {
111         COL_MIMETYPE = 0,
112         COL_SIZE     = 1,
113         COL_NAME     = 2
114 } AttachColumnPos;
115
116 #define N_ATTACH_COLS           3
117
118 #define B64_LINE_SIZE           57
119 #define B64_BUFFSIZE            77
120
121 #define MAX_REFERENCES_LEN      999
122
123 static GdkColor quote_color = {0, 0, 0, 0xbfff};
124
125 static GList *compose_list = NULL;
126
127 static Compose *compose_create                  (PrefsAccount   *account,
128                                                  ComposeMode     mode);
129 static void compose_toolbar_create              (Compose        *compose,
130                                                  GtkWidget      *container);
131 static GtkWidget *compose_account_option_menu_create
132                                                 (Compose        *compose);
133 static void compose_set_template_menu           (Compose        *compose);
134 static void compose_destroy                     (Compose        *compose);
135
136 static gint compose_parse_header                (Compose        *compose,
137                                                  MsgInfo        *msginfo);
138 static gchar *compose_parse_references          (const gchar    *ref,
139                                                  const gchar    *msgid);
140
141 static gchar *compose_quote_fmt                 (Compose        *compose,
142                                                  MsgInfo        *msginfo,
143                                                  const gchar    *fmt,
144                                                  const gchar    *qmark);
145
146 static void compose_reply_set_entry             (Compose        *compose,
147                                                  MsgInfo        *msginfo,
148                                                  gboolean        to_all,
149                                                  gboolean        to_sender,
150                                                  gboolean
151                                                  followup_and_reply_to);
152 static void compose_reedit_set_entry            (Compose        *compose,
153                                                  MsgInfo        *msginfo);
154 static void compose_insert_sig                  (Compose        *compose);
155 static void compose_insert_file                 (Compose        *compose,
156                                                  const gchar    *file);
157 static void compose_attach_append               (Compose        *compose,
158                                                  const gchar    *file,
159                                                  ContentType     cnttype);
160 static void compose_attach_append_with_type(Compose *compose,
161                                             const gchar *file,
162                                             const gchar *type,
163                                             ContentType cnttype);
164 static void compose_wrap_line                   (Compose        *compose);
165 static void compose_wrap_line_all               (Compose        *compose);
166 static void compose_set_title                   (Compose        *compose);
167
168 static PrefsAccount *compose_current_mail_account(void);
169 /* static gint compose_send                     (Compose        *compose); */
170 static gint compose_write_to_file               (Compose        *compose,
171                                                  const gchar    *file,
172                                                  gboolean        is_draft);
173 static gint compose_write_body_to_file          (Compose        *compose,
174                                                  const gchar    *file);
175 static gint compose_save_to_outbox              (Compose        *compose,
176                                                  const gchar    *file);
177 static gint compose_remove_reedit_target        (Compose        *compose);
178 static gint compose_queue                       (Compose        *compose,
179                                                  const gchar    *file);
180 static void compose_write_attach                (Compose        *compose,
181                                                  FILE           *fp);
182 static gint compose_write_headers               (Compose        *compose,
183                                                  FILE           *fp,
184                                                  const gchar    *charset,
185                                                  EncodingType    encoding,
186                                                  gboolean        is_draft);
187
188 static void compose_convert_header              (gchar          *dest,
189                                                  gint            len,
190                                                  gchar          *src,
191                                                  gint            header_len);
192 static void compose_generate_msgid              (Compose        *compose,
193                                                  gchar          *buf,
194                                                  gint            len);
195
196 static void compose_attach_info_free            (AttachInfo     *ainfo);
197 static void compose_attach_remove_selected      (Compose        *compose);
198
199 static void compose_attach_property             (Compose        *compose);
200 static void compose_attach_property_create      (gboolean       *cancelled);
201 static void attach_property_ok                  (GtkWidget      *widget,
202                                                  gboolean       *cancelled);
203 static void attach_property_cancel              (GtkWidget      *widget,
204                                                  gboolean       *cancelled);
205 static gint attach_property_delete_event        (GtkWidget      *widget,
206                                                  GdkEventAny    *event,
207                                                  gboolean       *cancelled);
208 static void attach_property_key_pressed         (GtkWidget      *widget,
209                                                  GdkEventKey    *event,
210                                                  gboolean       *cancelled);
211
212 static void compose_exec_ext_editor             (Compose           *compose);
213 static gint compose_exec_ext_editor_real        (const gchar       *file);
214 static gboolean compose_ext_editor_kill         (Compose           *compose);
215 static void compose_input_cb                    (gpointer           data,
216                                                  gint               source,
217                                                  GdkInputCondition  condition);
218 static void compose_set_ext_editor_sensitive    (Compose           *compose,
219                                                  gboolean           sensitive);
220
221 static gint calc_cursor_xpos    (GtkSText       *text,
222                                  gint            extra,
223                                  gint            char_width);
224
225 static void compose_create_header_entry (Compose *compose);
226 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
227
228 /* callback functions */
229
230 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
231                                          GtkAllocation  *allocation,
232                                          GtkSHRuler     *shruler);
233
234 static void toolbar_send_cb             (GtkWidget      *widget,
235                                          gpointer        data);
236 static void toolbar_send_later_cb       (GtkWidget      *widget,
237                                          gpointer        data);
238 static void toolbar_draft_cb            (GtkWidget      *widget,
239                                          gpointer        data);
240 static void toolbar_insert_cb           (GtkWidget      *widget,
241                                          gpointer        data);
242 static void toolbar_attach_cb           (GtkWidget      *widget,
243                                          gpointer        data);
244 static void toolbar_sig_cb              (GtkWidget      *widget,
245                                          gpointer        data);
246 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
247                                          gpointer        data);
248 static void toolbar_linewrap_cb         (GtkWidget      *widget,
249                                          gpointer        data);
250 static void toolbar_address_cb          (GtkWidget      *widget,
251                                          gpointer        data);
252 static void template_select_cb          (gpointer        daat,
253                                          guint           action,
254                                          GtkWidget      *widget);
255
256
257 static void select_account(Compose * compose, PrefsAccount * ac);
258 static void account_activated           (GtkMenuItem    *menuitem,
259                                          gpointer        data);
260
261 static void attach_selected             (GtkCList       *clist,
262                                          gint            row,
263                                          gint            column,
264                                          GdkEvent       *event,
265                                          gpointer        data);
266 static void attach_button_pressed       (GtkWidget      *widget,
267                                          GdkEventButton *event,
268                                          gpointer        data);
269 static void attach_key_pressed          (GtkWidget      *widget,
270                                          GdkEventKey    *event,
271                                          gpointer        data);
272
273 static void compose_send_cb             (gpointer        data,
274                                          guint           action,
275                                          GtkWidget      *widget);
276 static void compose_send_later_cb       (gpointer        data,
277                                          guint           action,
278                                          GtkWidget      *widget);
279
280 static void compose_draft_cb            (gpointer        data,
281                                          guint           action,
282                                          GtkWidget      *widget);
283
284 static void compose_attach_cb           (gpointer        data,
285                                          guint           action,
286                                          GtkWidget      *widget);
287 static void compose_insert_file_cb      (gpointer        data,
288                                          guint           action,
289                                          GtkWidget      *widget);
290
291 static void compose_close_cb            (gpointer        data,
292                                          guint           action,
293                                          GtkWidget      *widget);
294
295 static void compose_address_cb          (gpointer        data,
296                                          guint           action,
297                                          GtkWidget      *widget);
298 static void compose_template_activate_cb(GtkWidget      *widget,
299                                          gpointer        data);
300
301 static void compose_ext_editor_cb       (gpointer        data,
302                                          guint           action,
303                                          GtkWidget      *widget);
304
305 static gint compose_delete_cb           (GtkWidget      *widget,
306                                          GdkEventAny    *event,
307                                          gpointer        data);
308 static void compose_destroy_cb          (GtkWidget      *widget,
309                                          Compose        *compose);
310
311 static void compose_cut_cb              (Compose        *compose);
312 static void compose_copy_cb             (Compose        *compose);
313 static void compose_paste_cb            (Compose        *compose);
314 static void compose_allsel_cb           (Compose        *compose);
315
316 static void compose_grab_focus_cb       (GtkWidget      *widget,
317                                          Compose        *compose);
318
319 static void compose_changed_cb          (GtkEditable    *editable,
320                                          Compose        *compose);
321 static void compose_button_press_cb     (GtkWidget      *widget,
322                                          GdkEventButton *event,
323                                          Compose        *compose);
324 #if 0
325 static void compose_key_press_cb        (GtkWidget      *widget,
326                                          GdkEventKey    *event,
327                                          Compose        *compose);
328 #endif
329
330 static void compose_toggle_to_cb        (gpointer        data,
331                                          guint           action,
332                                          GtkWidget      *widget);
333 static void compose_toggle_cc_cb        (gpointer        data,
334                                          guint           action,
335                                          GtkWidget      *widget);
336 static void compose_toggle_bcc_cb       (gpointer        data,
337                                          guint           action,
338                                          GtkWidget      *widget);
339 static void compose_toggle_replyto_cb   (gpointer        data,
340                                          guint           action,
341                                          GtkWidget      *widget);
342 static void compose_toggle_followupto_cb(gpointer        data,
343                                          guint           action,
344                                          GtkWidget      *widget);
345 static void compose_toggle_attach_cb    (gpointer        data,
346                                          guint           action,
347                                          GtkWidget      *widget);
348 static void compose_toggle_ruler_cb     (gpointer        data,
349                                          guint           action,
350                                          GtkWidget      *widget);
351 #if USE_GPGME
352 static void compose_toggle_sign_cb      (gpointer        data,
353                                          guint           action,
354                                          GtkWidget      *widget);
355 static void compose_toggle_encrypt_cb   (gpointer        data,
356                                          guint           action,
357                                          GtkWidget      *widget);
358 #endif
359 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
360                                              GtkWidget *widget);
361
362 static void compose_attach_drag_received_cb (GtkWidget          *widget,
363                                              GdkDragContext     *drag_context,
364                                              gint                x,
365                                              gint                y,
366                                              GtkSelectionData   *data,
367                                              guint               info,
368                                              guint               time,
369                                              gpointer            user_data);
370 static void compose_insert_drag_received_cb (GtkWidget          *widget,
371                                              GdkDragContext     *drag_context,
372                                              gint                x,
373                                              gint                y,
374                                              GtkSelectionData   *data,
375                                              guint               info,
376                                              guint               time,
377                                              gpointer            user_data);
378
379 static void to_activated                (GtkWidget      *widget,
380                                          Compose        *compose);
381 static void newsgroups_activated        (GtkWidget      *widget,
382                                          Compose        *compose);
383 static void subject_activated           (GtkWidget      *widget,
384                                          Compose        *compose);
385 static void cc_activated                (GtkWidget      *widget,
386                                          Compose        *compose);
387 static void bcc_activated               (GtkWidget      *widget,
388                                          Compose        *compose);
389 static void replyto_activated           (GtkWidget      *widget,
390                                          Compose        *compose);
391 static void followupto_activated        (GtkWidget      *widget,
392                                          Compose        *compose);
393 static void compose_attach_parts(Compose * compose,
394                                  MsgInfo * msginfo);
395
396 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
397                                   gboolean to_all,
398                                   gboolean ignore_replyto,
399                                   gboolean followup_and_reply_to);
400
401 void compose_headerentry_changed_cb     (GtkWidget *entry,
402                                          compose_headerentry *headerentry);
403 void compose_headerentry_key_press_event_cb     (GtkWidget *entry,
404                                                  GdkEventKey *event,
405                                                  compose_headerentry *headerentry);
406
407 Compose * compose_generic_new (PrefsAccount     *account,
408                                const gchar      *to,
409                                FolderItem       *item);
410
411 static GtkItemFactoryEntry compose_popup_entries[] =
412 {
413         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
414         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
415         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
416         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
417 };
418
419 static GtkItemFactoryEntry compose_entries[] =
420 {
421         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
422         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb,      0, NULL},
423         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
424         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig,     0, NULL},
425         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
426         {N_("/_File/_Close"),                   "<alt>W", compose_close_cb, 0, NULL},
427
428         {N_("/_Edit"),             NULL, NULL, 0, "<Branch>"},
429         {N_("/_Edit/_Undo"),       "<control>Z", NULL, 0, NULL},
430         {N_("/_Edit/_Redo"),       "<control>Y", NULL, 0, NULL},
431         {N_("/_Edit/---"),         NULL, NULL, 0, "<Separator>"},
432         {N_("/_Edit/Cu_t"),        "<control>X", compose_cut_cb,    0, NULL},
433         {N_("/_Edit/_Copy"),       "<control>C", compose_copy_cb,   0, NULL},
434         {N_("/_Edit/_Paste"),      "<control>V", compose_paste_cb,  0, NULL},
435         {N_("/_Edit/Select _all"), "<control>A", compose_allsel_cb, 0, NULL},
436         {N_("/_Edit/---"),         NULL, NULL, 0, "<Separator>"},
437         {N_("/_Edit/_Wrap current paragraph"), "<alt>L", compose_wrap_line, 0, NULL},
438         {N_("/_Edit/Wrap all long _lines"),
439                         "<shift><alt>L", compose_wrap_line_all, 0, NULL},
440         {N_("/_Edit/Edit with e_xternal editor"),
441                         "<alt>X", compose_ext_editor_cb, 0, NULL},
442
443         {N_("/_Message"),               NULL, NULL, 0, "<Branch>"},
444         {N_("/_Message/_Send"),         "<control>Return",
445                                         compose_send_cb, 0, NULL},
446         {N_("/_Message/Send _later"),   "<shift><alt>S",
447                                         compose_send_later_cb,  0, NULL},
448         {N_("/_Message/Save to _draft folder"),
449                                         "<alt>D", compose_draft_cb, 0, NULL},
450 #if 0 /* NEW COMPOSE GUI */
451         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
452         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
453         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
454         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
455         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
456         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
457         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
458         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
459         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
460 #endif
461 #if USE_GPGME
462         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
463         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
464         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
465 #endif /* USE_GPGME */
466         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
467         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
468         {N_("/_Tool"),                  NULL, NULL, 0, "<Branch>"},
469         {N_("/_Tool/Show _ruler"),      NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
470         {N_("/_Tool/_Address book"),    "<alt>A", compose_address_cb , 0, NULL},
471         {N_("/_Tool/_Template"),        NULL, NULL, 0, "<Branch>"},
472         {N_("/_Help"),                  NULL, NULL, 0, "<LastBranch>"},
473         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
474 };
475
476 static GtkTargetEntry compose_mime_types[] =
477 {
478         {"text/uri-list", 0, 0}
479 };
480
481 Compose * compose_new(PrefsAccount *account)
482 {
483         return compose_generic_new(account, NULL, NULL);
484 }
485
486 Compose * compose_new_with_recipient(PrefsAccount *account, const gchar *to)
487 {
488         return compose_generic_new(account, to, NULL);
489 }
490
491 Compose * compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
492 {
493         return compose_generic_new(account, NULL, item);
494 }
495
496 static void set_compose_entries(Compose * compose, const gchar * mailto)
497 {
498         gchar * subject = NULL;
499         gchar * to = NULL;
500         gchar * cc = NULL;
501         gchar * bcc = NULL;
502         gchar * body = NULL;
503         gchar * p;
504         gchar * tmp_mailto;
505         gchar * cur;
506         
507         Xstrdup_a(tmp_mailto, mailto, return);
508
509         cur = tmp_mailto;
510
511         p = strchr(cur, '?');
512         if (p != NULL) {
513                 * p = 0;
514                 cur = p + 1;
515         }
516         to = tmp_mailto;
517
518         while (p) {
519                 char *field, *value;
520                 
521                 field = cur;
522
523                 p = strchr(cur, '=');
524                 if (p == NULL)
525                         break;
526                 * p = 0;
527                 cur = p + 1;
528
529                 value = cur;
530
531                 p = strchr(cur, '&');
532                 if (p != NULL) {
533                         * p = 0;
534                         cur = p + 1;
535                 }
536
537                 if (value) {
538                         if (g_strcasecmp(field, "subject")==0) {
539                                 Xstrdup_a(subject, value, );
540                                 if (subject != NULL)
541                                         decode_uri(subject, value);
542                         }
543                         else if (g_strcasecmp(field, "cc")==0)
544                                 cc = value;
545                         else if (g_strcasecmp(field, "bcc")==0)
546                                 bcc = value;
547                         else if (g_strcasecmp(field, "body")==0) {
548                                 Xstrdup_a(body, value, );
549                                 if (body != NULL)
550                                         decode_uri(body, value);
551                         }
552                 }
553         }                       
554
555         if (to) {
556                 compose_entry_append(compose, to, COMPOSE_TO);
557                 /*
558                 gtk_widget_grab_focus(compose->text);
559                 */
560         }
561
562         if (subject)
563                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
564         if (cc)
565                 compose_entry_append(compose, cc, COMPOSE_CC);
566         if (bcc)
567                 compose_entry_append(compose, bcc, COMPOSE_BCC);
568         if (body) {
569                 gtk_stext_insert(GTK_STEXT(compose->text),
570                                  NULL, NULL, NULL, body, -1);
571                 gtk_stext_insert(GTK_STEXT(compose->text),
572                                  NULL, NULL, NULL, "\n", 1);
573         }
574 }       
575
576 Compose * compose_generic_new(PrefsAccount *account, const gchar *to, FolderItem *item)
577 {
578         Compose *compose;
579
580         if (item && item->prefs && item->prefs->enable_default_account)
581                 account = account_find_from_id(item->prefs->default_account);
582
583         if (!account) account = cur_account;
584         g_return_val_if_fail(account != NULL, NULL);
585
586         compose = compose_create(account, COMPOSE_NEW);
587         compose->replyinfo = NULL;
588
589         if (prefs_common.auto_sig)
590                 compose_insert_sig(compose);
591         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
592         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
593
594         if (account->protocol != A_NNTP) {
595                 if (to) {
596                         set_compose_entries(compose, to);
597
598                 } else if(item && item->prefs->enable_default_to) {
599                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
600                 }
601                 if (item && item->ret_rcpt) {
602                         GtkItemFactory *ifactory;
603                 
604                         ifactory = gtk_item_factory_from_widget(compose->menubar);
605                         menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
606                 }
607         } else {
608                 if (to) {
609                         compose_entry_append(compose, to, COMPOSE_NEWSGROUPS);
610                 }
611         }
612         gtk_widget_grab_focus(compose->subject_entry);
613
614         if (prefs_common.auto_exteditor)
615                 compose_exec_ext_editor(compose);
616
617         return compose;
618 }
619
620 #define CHANGE_FLAGS(msginfo) \
621 { \
622 if (msginfo->folder->folder->change_flags != NULL) \
623 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
624                                       msginfo->folder, \
625                                       msginfo); \
626 }
627
628 /*
629 Compose * compose_new_followup_and_replyto(PrefsAccount *account,
630                                            const gchar *followupto, gchar * to)
631 {
632         Compose *compose;
633
634         if (!account) account = cur_account;
635         g_return_val_if_fail(account != NULL, NULL);
636         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
637
638         compose = compose_create(account, COMPOSE_NEW);
639
640         if (prefs_common.auto_sig)
641                 compose_insert_sig(compose);
642         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
643         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
644
645         compose_entry_append(compose, to, COMPOSE_TO);
646         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
647         gtk_widget_grab_focus(compose->subject_entry);
648
649         return compose;
650 }
651 */
652
653 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
654                    gboolean ignore_replyto)
655 {
656         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, FALSE);
657 }
658
659 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
660                                    gboolean to_all,
661                                    gboolean ignore_replyto)
662 {
663         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, TRUE);
664 }
665
666 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
667                                   gboolean to_all,
668                                   gboolean ignore_replyto,
669                                   gboolean followup_and_reply_to)
670 {
671         Compose *compose;
672         PrefsAccount *account;
673         PrefsAccount *reply_account;
674         GtkSText *text;
675
676         g_return_if_fail(msginfo != NULL);
677         g_return_if_fail(msginfo->folder != NULL);
678
679         account = NULL;
680         /* select the account set in folderitem's property (if enabled) */
681         if (msginfo->folder->prefs && msginfo->folder->prefs->enable_default_account)
682                 account = account_find_from_id(msginfo->folder->prefs->default_account);
683         
684         /* select the account for the whole folder (IMAP / NNTP) */
685         if (!account)
686                 account = msginfo->folder->folder->account;
687
688         /* select account by to: and cc: header if enabled */
689         if (prefs_common.reply_account_autosel) {
690                 if (!account && msginfo->to) {
691                         gchar *to;
692                         Xstrdup_a(to, msginfo->to, return);
693                         extract_address(to);
694                         account = account_find_from_address(to);
695                 }
696                 if (!account) {
697                         gchar cc[BUFFSIZE];
698                         if(!get_header_from_msginfo(msginfo, cc, sizeof(cc), "CC:")) { /* Found a CC header */
699                                 extract_address(cc);
700                                 account = account_find_from_address(cc);
701                         }        
702                 }
703         }
704
705         /* select current account */
706         if (!account) account = cur_account;
707         g_return_if_fail(account != NULL);
708
709         if (ignore_replyto && account->protocol == A_NNTP &&
710             !followup_and_reply_to) {
711                 reply_account =
712                         account_find_from_address(account->address);
713                 if (!reply_account)
714                         reply_account = compose_current_mail_account();
715                 if (!reply_account)
716                         return;
717         } else
718                 reply_account = account;
719
720         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
721         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
722
723         CHANGE_FLAGS(msginfo);
724
725         compose = compose_create(account, COMPOSE_REPLY);
726         compose->replyinfo = procmsg_msginfo_copy(msginfo);
727
728 #if 0 /* NEW COMPOSE GUI */
729         if (followup_and_reply_to) {
730                 gtk_widget_show(compose->to_hbox);
731                 gtk_widget_show(compose->to_entry);
732                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
733                 compose->use_to = TRUE;
734         }
735 #endif
736         if (msginfo->folder && msginfo->folder->ret_rcpt) {
737                 GtkItemFactory *ifactory;
738         
739                 ifactory = gtk_item_factory_from_widget(compose->menubar);
740                 menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
741         }
742
743         if (compose_parse_header(compose, msginfo) < 0) return;
744         compose_reply_set_entry(compose, msginfo, to_all, ignore_replyto,
745                                 followup_and_reply_to);
746
747         text = GTK_STEXT(compose->text);
748         gtk_stext_freeze(text);
749
750         if (quote) {
751                 gchar *qmark;
752                 gchar *quote_str;
753
754                 if (prefs_common.quotemark && *prefs_common.quotemark)
755                         qmark = prefs_common.quotemark;
756                 else
757                         qmark = "> ";
758
759                 quote_str = compose_quote_fmt(compose, msginfo,
760                                               prefs_common.quotefmt,
761                                               qmark);
762         }
763
764         if (prefs_common.auto_sig)
765                 compose_insert_sig(compose);
766         gtk_editable_set_position(GTK_EDITABLE(text), 0);
767         gtk_stext_set_point(text, 0);
768
769         if (quote && prefs_common.linewrap_quote) {
770                 compose_wrap_line_all(compose);
771         }
772
773         gtk_stext_thaw(text);
774         gtk_widget_grab_focus(compose->text);
775
776         if (prefs_common.auto_exteditor)
777                 compose_exec_ext_editor(compose);
778 }
779
780
781 static gchar *procmime_get_file_name(MimeInfo *mimeinfo)
782 {
783         gchar *base;
784         gchar *filename;
785
786         g_return_val_if_fail(mimeinfo != NULL, NULL);
787
788         base = mimeinfo->filename ? mimeinfo->filename
789                 : mimeinfo->name ? mimeinfo->name : NULL;
790
791         if (MIME_TEXT_HTML == mimeinfo->mime_type && base == NULL){
792                 filename = g_strdup_printf("%s%smimetmp%i.html",
793                                            get_mime_tmp_dir(),
794                                            G_DIR_SEPARATOR_S,
795                                            mimeinfo);
796                 return filename;
797         }
798         else {
799                 base = base ? base : "";
800                 base = g_basename(base);
801                 if (*base == '\0') {
802                         filename = g_strdup_printf("%s%smimetmp%i",
803                                                    get_mime_tmp_dir(),
804                                                    G_DIR_SEPARATOR_S,
805                                                    mimeinfo);
806                         return filename;
807                 }
808         }
809
810         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
811                                base, NULL);
812
813         return filename;
814 }
815
816 static gchar * mime_extract_file(gchar * source, MimeInfo *partinfo)
817 {
818         gchar *filename;
819
820         if (!partinfo) return;
821
822         filename = procmime_get_file_name(partinfo);
823
824         if (procmime_get_part(filename, source, partinfo) < 0)
825                 alertpanel_error
826                         (_("Can't get the part of multipart message."));
827
828         return filename;
829 }
830
831 static void compose_attach_parts(Compose * compose,
832                                  MsgInfo * msginfo)
833 {
834
835         FILE *fp;
836         gchar *file;
837         MimeInfo *mimeinfo;
838         MsgInfo *tmpmsginfo;
839         gchar *p;
840         gchar *boundary;
841         gint boundary_len = 0;
842         gchar buf[BUFFSIZE];
843         glong fpos, prev_fpos;
844         gint npart;
845         gchar * source;
846         gchar * filename;
847
848         g_return_if_fail(msginfo != NULL);
849         
850 #if USE_GPGME
851         for (;;) {
852                 if ((fp = procmsg_open_message(msginfo)) == NULL) return;
853                 mimeinfo = procmime_scan_mime_header(fp);
854                 if (!mimeinfo) break;
855
856                 if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
857                     rfc2015_is_encrypted(mimeinfo)) {
858                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
859                 }
860                 if (MSG_IS_ENCRYPTED(msginfo->flags) &&
861                     !msginfo->plaintext_file  &&
862                     !msginfo->decryption_failed) {
863                         rfc2015_decrypt_message(msginfo, mimeinfo, fp);
864                         if (msginfo->plaintext_file &&
865                             !msginfo->decryption_failed) {
866                                 fclose(fp);
867                                 continue;
868                         }
869                 }
870                 
871                 break;
872         }
873 #else /* !USE_GPGME */
874         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
875         mimeinfo = procmime_scan_mime_header(fp);
876 #endif /* USE_GPGME */
877
878         fclose(fp);
879         if (!mimeinfo) return;
880         if (mimeinfo->mime_type == MIME_TEXT)
881                 return;
882
883         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
884
885         g_return_if_fail(mimeinfo != NULL);
886         g_return_if_fail(mimeinfo->mime_type != MIME_TEXT);
887
888         if (mimeinfo->mime_type == MIME_MULTIPART) {
889                 g_return_if_fail(mimeinfo->boundary != NULL);
890                 g_return_if_fail(mimeinfo->sub == NULL);
891         }
892         g_return_if_fail(fp != NULL);
893
894         boundary = mimeinfo->boundary;
895
896         if (boundary) {
897                 boundary_len = strlen(boundary);
898
899                 /* look for first boundary */
900                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL)
901                         if (IS_BOUNDARY(buf, boundary, boundary_len)) break;
902                 if (!p) {
903                         fclose(fp);
904                         return;
905                 }
906         }
907
908         if ((fpos = ftell(fp)) < 0) {
909                 perror("ftell");
910                 fclose(fp);
911                 return;
912         }
913
914         for (npart = 0;; npart++) {
915                 MimeInfo *partinfo;
916                 gboolean eom = FALSE;
917
918                 prev_fpos = fpos;
919
920                 partinfo = procmime_scan_mime_header(fp);
921                 if (!partinfo) break;
922
923                 if (npart != 0)
924                         procmime_mimeinfo_insert(mimeinfo, partinfo);
925                 else
926                         procmime_mimeinfo_free(partinfo);
927
928                 /* look for next boundary */
929                 buf[0] = '\0';
930                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
931                         if (IS_BOUNDARY(buf, boundary, boundary_len)) {
932                                 if (buf[2 + boundary_len]     == '-' &&
933                                     buf[2 + boundary_len + 1] == '-')
934                                         eom = TRUE;
935                                 break;
936                         }
937                 }
938                 if (p == NULL)
939                         eom = TRUE;     /* broken MIME message */
940                 fpos = ftell(fp);
941
942                 partinfo->size = fpos - prev_fpos - strlen(buf);
943
944                 if (eom) break;
945         }
946
947         source = procmsg_get_message_file_path(msginfo);
948
949         g_return_if_fail(mimeinfo != NULL);
950
951         if (!mimeinfo->main && mimeinfo->parent)
952                 {
953                         filename = mime_extract_file(source, mimeinfo);
954
955                         compose_attach_append_with_type(compose, filename,
956                                                         mimeinfo->content_type,
957                                                         mimeinfo->mime_type);
958
959                         g_free(filename);
960                 }
961
962         if (mimeinfo->sub && mimeinfo->sub->children)
963                 {
964                         filename = mime_extract_file(source, mimeinfo->sub);
965
966                         compose_attach_append_with_type(compose, filename,
967                                                         mimeinfo->content_type,
968                                                         mimeinfo->sub->mime_type);
969
970                         g_free(filename);
971                 }
972
973         if (mimeinfo->children) {
974                 MimeInfo *child;
975
976                 child = mimeinfo->children;
977                 while (child) {
978                         filename = mime_extract_file(source, child);
979
980                         compose_attach_append_with_type(compose, filename,
981                                                         child->content_type,
982                                                         child->mime_type);
983
984                         g_free(filename);
985
986                         child = child->next;
987                 }
988         }
989
990         fclose(fp);
991
992         procmime_mimeinfo_free_all(mimeinfo);
993 }
994
995
996 #define INSERT_FW_HEADER(var, hdr) \
997 if (msginfo->var && *msginfo->var) { \
998         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
999         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1000         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1001 }
1002
1003 Compose *compose_forward(PrefsAccount * account, MsgInfo *msginfo,
1004                          gboolean as_attach)
1005 {
1006         Compose *compose;
1007         /*      PrefsAccount *account; */
1008         GtkSText *text;
1009
1010         g_return_val_if_fail(msginfo != NULL, NULL);
1011         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1012
1013         account = msginfo->folder->folder->account;
1014         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
1015                 gchar *to;
1016                 Xstrdup_a(to, msginfo->to, return);
1017                 extract_address(to);
1018                 account = account_find_from_address(to);
1019         }
1020
1021         if(!account && prefs_common.forward_account_autosel) {
1022                 gchar cc[BUFFSIZE];
1023                 if(!get_header_from_msginfo(msginfo,cc,sizeof(cc),"CC:")){ /* Found a CC header */
1024                         extract_address(cc);
1025                         account = account_find_from_address(cc);
1026                 }
1027         }
1028
1029         if (account == NULL) {
1030                 account = cur_account;
1031                 /*
1032                 account = msginfo->folder->folder->account;
1033                 if (!account) account = cur_account;
1034                 */
1035         }
1036         g_return_val_if_fail(account != NULL, NULL);
1037
1038         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
1039         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
1040         CHANGE_FLAGS(msginfo);
1041
1042         compose = compose_create(account, COMPOSE_FORWARD);
1043
1044         if (msginfo->subject && *msginfo->subject) {
1045                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
1046                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
1047                                       msginfo->subject);
1048         }
1049
1050         text = GTK_STEXT(compose->text);
1051         gtk_stext_freeze(text);
1052
1053         if (as_attach) {
1054                 gchar *msgfile;
1055
1056                 msgfile = procmsg_get_message_file_path(msginfo);
1057                 if (!is_file_exist(msgfile))
1058                         g_warning(_("%s: file not exist\n"), msgfile);
1059                 else
1060                         compose_attach_append(compose, msgfile,
1061                                               MIME_MESSAGE_RFC822);
1062
1063                 g_free(msgfile);
1064         } else {
1065                 gchar *qmark;
1066                 gchar *quote_str;
1067
1068                 if (prefs_common.fw_quotemark && *prefs_common.fw_quotemark)
1069                         qmark = prefs_common.quotemark;
1070                 else
1071                         qmark = "> ";
1072
1073                 quote_str = compose_quote_fmt(compose, msginfo,
1074                                               prefs_common.fw_quotefmt, qmark);
1075                 compose_attach_parts(compose, msginfo);
1076         }
1077
1078         if (prefs_common.auto_sig)
1079                 compose_insert_sig(compose);
1080         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1081         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1082
1083         gtk_stext_thaw(text);
1084 #if 0 /* NEW COMPOSE GUI */
1085         if (account->protocol != A_NNTP)
1086                 gtk_widget_grab_focus(compose->to_entry);
1087         else
1088                 gtk_widget_grab_focus(compose->newsgroups_entry);
1089 #endif
1090         gtk_widget_grab_focus(compose->header_last->entry);
1091
1092         if (prefs_common.auto_exteditor)
1093                 compose_exec_ext_editor(compose);
1094
1095         return compose;
1096 }
1097
1098 #undef INSERT_FW_HEADER
1099
1100 Compose * compose_forward_multiple(PrefsAccount * account, 
1101                           GSList *msginfo_list) 
1102 {
1103         Compose *compose;
1104         GtkSText *text;
1105         GSList *msginfo;
1106         gchar *msgfile;
1107
1108         g_return_val_if_fail(msginfo_list != NULL, NULL);
1109         
1110         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1111                 if ( ((MsgInfo *)msginfo->data)->folder == NULL )
1112                         return NULL;
1113         }
1114
1115         if (account == NULL) {
1116                 account = cur_account;
1117                 /*
1118                 account = msginfo->folder->folder->account;
1119                 if (!account) account = cur_account;
1120                 */
1121         }
1122         g_return_val_if_fail(account != NULL, NULL);
1123
1124         compose = compose_create(account, COMPOSE_FORWARD);
1125
1126         text = GTK_STEXT(compose->text);
1127         gtk_stext_freeze(text);
1128
1129         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1130                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1131                 if (!is_file_exist(msgfile))
1132                         g_warning(_("%s: file not exist\n"), msgfile);
1133                 else
1134                         compose_attach_append(compose, msgfile,
1135                                 MIME_MESSAGE_RFC822);
1136                 g_free(msgfile);
1137         }
1138
1139         if (prefs_common.auto_sig)
1140                 compose_insert_sig(compose);
1141         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1142         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1143
1144         gtk_stext_thaw(text);
1145 #if 0 /* NEW COMPOSE GUI */
1146         if (account->protocol != A_NNTP)
1147                 gtk_widget_grab_focus(compose->to_entry);
1148         else
1149                 gtk_widget_grab_focus(compose->newsgroups_entry);
1150 #endif
1151
1152         return compose;
1153 }
1154
1155 void compose_reedit(MsgInfo *msginfo)
1156 {
1157         Compose *compose;
1158         PrefsAccount *account;
1159         GtkSText *text;
1160         FILE *fp;
1161         gchar buf[BUFFSIZE];
1162
1163         g_return_if_fail(msginfo != NULL);
1164         g_return_if_fail(msginfo->folder != NULL);
1165
1166         account = msginfo->folder->folder->account;
1167
1168         if(!account&& prefs_common.reedit_account_autosel) {
1169                 gchar from[BUFFSIZE];
1170                 if(!get_header_from_msginfo(msginfo,from,sizeof(from),"FROM:")){ /* Found a FROM header */
1171                         extract_address(from);
1172                         account = account_find_from_address(from);
1173                 }
1174         }
1175         if (!account) account = cur_account;
1176         g_return_if_fail(account != NULL);
1177
1178         compose = compose_create(account, COMPOSE_REEDIT);
1179         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1180
1181         if (compose_parse_header(compose, msginfo) < 0) return;
1182         compose_reedit_set_entry(compose, msginfo);
1183
1184         text = GTK_STEXT(compose->text);
1185         gtk_stext_freeze(text);
1186
1187         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1188                 g_warning(_("Can't get text part\n"));
1189         else {
1190                 while (fgets(buf, sizeof(buf), fp) != NULL)
1191                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1192                 fclose(fp);
1193         }
1194         compose_attach_parts(compose, msginfo);
1195
1196         gtk_stext_thaw(text);
1197         gtk_widget_grab_focus(compose->text);
1198
1199         if (prefs_common.auto_exteditor)
1200                 compose_exec_ext_editor(compose);
1201 }
1202
1203 GList *compose_get_compose_list(void)
1204 {
1205         return compose_list;
1206 }
1207
1208 void compose_entry_append(Compose *compose, const gchar *address,
1209                           ComposeEntryType type)
1210 {
1211         GtkEntry *entry;
1212         const gchar *text;
1213         gchar *header;
1214
1215         if (!address || *address == '\0') return;
1216
1217 #if 0 /* NEW COMPOSE GUI */
1218         switch (type) {
1219         case COMPOSE_CC:
1220                 entry = GTK_ENTRY(compose->cc_entry);
1221                 break;
1222         case COMPOSE_BCC:
1223                 entry = GTK_ENTRY(compose->bcc_entry);
1224                 break;
1225         case COMPOSE_NEWSGROUPS:
1226                 entry = GTK_ENTRY(compose->newsgroups_entry);
1227                 break;
1228         case COMPOSE_TO:
1229         default:
1230                 entry = GTK_ENTRY(compose->to_entry);
1231                 break;
1232         }
1233
1234         text = gtk_entry_get_text(entry);
1235         if (*text != '\0')
1236                 gtk_entry_append_text(entry, ", ");
1237         gtk_entry_append_text(entry, address);
1238 #endif
1239
1240         switch (type) {
1241         case COMPOSE_CC:
1242                 header = N_("Cc:");
1243                 break;
1244         case COMPOSE_BCC:
1245                 header = N_("Bcc:");
1246                 break;
1247         case COMPOSE_REPLYTO:
1248                 header = N_("Reply-To:");
1249                 break;
1250         case COMPOSE_NEWSGROUPS:
1251                 header = N_("Newsgroups:");
1252                 break;
1253         case COMPOSE_FOLLOWUPTO:
1254                 header = N_( "Followup-To:");
1255                 break;
1256         case COMPOSE_TO:
1257         default:
1258                 header = N_("To:");
1259                 break;
1260         }
1261         header = prefs_common.trans_hdr ? gettext(header) : header;
1262
1263         compose_add_header_entry(compose, header, (gchar *)address);
1264 }
1265
1266 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1267 {
1268         static HeaderEntry hentry[] = {{"Reply-To:",       NULL, TRUE},
1269                                        {"Cc:",             NULL, FALSE},
1270                                        {"References:",     NULL, FALSE},
1271                                        {"Bcc:",            NULL, FALSE},
1272                                        {"Newsgroups:",     NULL, FALSE},
1273                                        {"Followup-To:",    NULL, FALSE},
1274                                        {"X-Mailing-List:", NULL, FALSE},
1275                                        {"X-BeenThere:",    NULL, FALSE},
1276                                        {NULL,              NULL, FALSE}};
1277
1278         enum
1279         {
1280                 H_REPLY_TO       = 0,
1281                 H_CC             = 1,
1282                 H_REFERENCES     = 2,
1283                 H_BCC            = 3,
1284                 H_NEWSGROUPS     = 4,
1285                 H_FOLLOWUP_TO    = 5,
1286                 H_X_MAILING_LIST = 6,
1287                 H_X_BEENTHERE    = 7
1288         };
1289
1290         FILE *fp;
1291
1292         g_return_val_if_fail(msginfo != NULL, -1);
1293
1294         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1295         procheader_get_header_fields(fp, hentry);
1296         fclose(fp);
1297
1298         if (hentry[H_REPLY_TO].body != NULL) {
1299                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1300                 compose->replyto = hentry[H_REPLY_TO].body;
1301                 hentry[H_REPLY_TO].body = NULL;
1302         }
1303         if (hentry[H_CC].body != NULL) {
1304                 conv_unmime_header_overwrite(hentry[H_CC].body);
1305                 compose->cc = hentry[H_CC].body;
1306                 hentry[H_CC].body = NULL;
1307         }
1308         if (hentry[H_X_MAILING_LIST].body != NULL) {
1309                 /* this is good enough to parse debian-devel */
1310                 char * buf = g_malloc(strlen(hentry[H_X_MAILING_LIST].body) + 1);
1311                 g_return_val_if_fail(buf != NULL, -1 );
1312                 if (1 == sscanf(hentry[H_X_MAILING_LIST].body, "<%[^>]>", buf))
1313                         compose->mailinglist = g_strdup(buf);
1314                 g_free(buf);
1315                 g_free(hentry[H_X_MAILING_LIST].body);
1316                 hentry[H_X_MAILING_LIST].body = NULL ;
1317         }
1318         if (hentry[H_X_BEENTHERE].body != NULL) {
1319                 /* this is good enough to parse the sylpheed-claws lists */
1320                 char * buf = g_malloc(strlen(hentry[H_X_BEENTHERE].body) + 1);
1321                 g_return_val_if_fail(buf != NULL, -1 );
1322                 if (1 == sscanf(hentry[H_X_BEENTHERE].body, "%[^>]", buf))
1323                         compose->mailinglist = g_strdup(buf);
1324                 g_free(buf);
1325                 g_free(hentry[H_X_BEENTHERE].body);
1326                 hentry[H_X_BEENTHERE].body = NULL ;
1327         }
1328         if (hentry[H_REFERENCES].body != NULL) {
1329                 if (compose->mode == COMPOSE_REEDIT)
1330                         compose->references = hentry[H_REFERENCES].body;
1331                 else {
1332                         compose->references = compose_parse_references
1333                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1334                         g_free(hentry[H_REFERENCES].body);
1335                 }
1336                 hentry[H_REFERENCES].body = NULL;
1337         }
1338         if (hentry[H_BCC].body != NULL) {
1339                 if (compose->mode == COMPOSE_REEDIT) {
1340                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1341                         compose->bcc = hentry[H_BCC].body;
1342                 } else
1343                         g_free(hentry[H_BCC].body);
1344                 hentry[H_BCC].body = NULL;
1345         }
1346         if (hentry[H_NEWSGROUPS].body != NULL) {
1347                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1348                 hentry[H_NEWSGROUPS].body = NULL;
1349         }
1350         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1351                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1352                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1353                 hentry[H_FOLLOWUP_TO].body = NULL;
1354         }
1355
1356         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1357                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1358         else if (compose->mode != COMPOSE_REEDIT &&
1359                  msginfo->msgid && *msginfo->msgid) {
1360                 compose->inreplyto = g_strdup(msginfo->msgid);
1361
1362                 if (!compose->references) {
1363                         if (msginfo->inreplyto && *msginfo->inreplyto)
1364                                 compose->references =
1365                                         g_strdup_printf("<%s>\n\t<%s>",
1366                                                         msginfo->inreplyto,
1367                                                         msginfo->msgid);
1368                         else
1369                                 compose->references =
1370                                         g_strconcat("<", msginfo->msgid, ">",
1371                                                     NULL);
1372                 }
1373         }
1374
1375         return 0;
1376 }
1377
1378 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1379 {
1380         GSList *ref_id_list, *cur;
1381         GString *new_ref;
1382         gchar *new_ref_str;
1383
1384         ref_id_list = references_list_append(NULL, ref);
1385         if (!ref_id_list) return NULL;
1386         if (msgid && *msgid)
1387                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1388
1389         for (;;) {
1390                 gint len = 0;
1391
1392                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1393                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1394                         len += strlen((gchar *)cur->data) + 5;
1395
1396                 if (len > MAX_REFERENCES_LEN) {
1397                         /* remove second message-ID */
1398                         if (ref_id_list && ref_id_list->next &&
1399                             ref_id_list->next->next) {
1400                                 g_free(ref_id_list->next->data);
1401                                 ref_id_list = g_slist_remove
1402                                         (ref_id_list, ref_id_list->next->data);
1403                         } else {
1404                                 slist_free_strings(ref_id_list);
1405                                 g_slist_free(ref_id_list);
1406                                 return NULL;
1407                         }
1408                 } else
1409                         break;
1410         }
1411
1412         new_ref = g_string_new("");
1413         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1414                 if (new_ref->len > 0)
1415                         g_string_append(new_ref, "\n\t");
1416                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1417         }
1418
1419         slist_free_strings(ref_id_list);
1420         g_slist_free(ref_id_list);
1421
1422         new_ref_str = new_ref->str;
1423         g_string_free(new_ref, FALSE);
1424
1425         return new_ref_str;
1426 }
1427
1428 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1429                                 const gchar *fmt, const gchar *qmark)
1430 {
1431         GtkSText *text = GTK_STEXT(compose->text);
1432         gchar *quote_str = NULL;
1433         gchar *buf;
1434         gchar *p, *lastp;
1435         gint len;
1436
1437         if (qmark != NULL) {
1438                 quote_fmt_init(msginfo, NULL);
1439                 quote_fmt_scan_string(qmark);
1440                 quote_fmt_parse();
1441
1442                 buf = quote_fmt_get_buffer();
1443                 if (buf == NULL)
1444                         alertpanel_error(_("Quote mark format error."));
1445                 else
1446                         Xstrdup_a(quote_str, buf, return NULL)
1447         }
1448
1449         quote_fmt_init(msginfo, quote_str);
1450         quote_fmt_scan_string(fmt);
1451         quote_fmt_parse();
1452
1453         buf = quote_fmt_get_buffer();
1454         if (buf == NULL) {
1455                 alertpanel_error(_("Message reply/forward format error."));
1456                 return NULL;
1457         }
1458
1459         gtk_stext_freeze(text);
1460         gtk_stext_set_point(text, 0);
1461         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
1462
1463         for (p = buf; *p != '\0'; ) {
1464                 lastp = strchr(p, '\n');
1465                 len = lastp ? lastp - p + 1 : -1;
1466                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1467                 if (lastp)
1468                         p = lastp + 1;
1469                 else
1470                         break;
1471         }
1472
1473         gtk_stext_thaw(text);
1474
1475         return buf;
1476 }
1477
1478 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1479                                     gboolean to_all, gboolean ignore_replyto,
1480                                     gboolean followup_and_reply_to)
1481 {
1482         GSList *cc_list;
1483         GSList *cur;
1484         gchar *from;
1485         GHashTable *to_table;
1486
1487         g_return_if_fail(compose->account != NULL);
1488         g_return_if_fail(msginfo != NULL);
1489
1490         if ((compose->account->protocol != A_NNTP) || followup_and_reply_to)
1491                 compose_entry_append(compose,
1492                                     ((compose->mailinglist && !ignore_replyto)
1493                                      ? compose->mailinglist
1494                                      : (compose->replyto && !ignore_replyto)
1495                                      ? compose->replyto
1496                                      : msginfo->from ? msginfo->from : ""),
1497                                      COMPOSE_TO);
1498         if (compose->account->protocol == A_NNTP)
1499                 if (ignore_replyto)
1500                         compose_entry_append(compose,
1501                                              msginfo->from ? msginfo->from : "",
1502                                              COMPOSE_TO);
1503                 else
1504                         compose_entry_append(compose,
1505                                              compose->followup_to ? compose->followup_to
1506                                              : compose->newsgroups ? compose->newsgroups
1507                                              : "",
1508                                              COMPOSE_NEWSGROUPS);
1509         /*
1510                 compose_entry_append(compose,
1511                                      compose->followup_to ? compose->followup_to
1512                                      : compose->newsgroups ? compose->newsgroups
1513                                      : "",
1514                                      COMPOSE_NEWSGROUPS);
1515         */
1516
1517         if (msginfo->subject && *msginfo->subject) {
1518                 gchar *buf, *buf2, *p;
1519
1520                 buf = g_strdup(msginfo->subject);
1521                 while (!strncasecmp(buf, "Re:", 3)) {
1522                         p = buf + 3;
1523                         while (isspace(*p)) p++;
1524                         memmove(buf, p, strlen(p) + 1);
1525                 }
1526
1527                 buf2 = g_strdup_printf("Re: %s", buf);
1528                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1529                 g_free(buf2);
1530                 g_free(buf);
1531         } else
1532                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1533
1534         if (!to_all || compose->account->protocol == A_NNTP) return;
1535
1536         from = g_strdup(compose->replyto ? compose->replyto :
1537                         msginfo->from ? msginfo->from : "");
1538         extract_address(from);
1539
1540         cc_list = address_list_append(NULL, msginfo->to);
1541         cc_list = address_list_append(cc_list, compose->cc);
1542
1543         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1544         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1545         if (compose->account)
1546                 g_hash_table_insert(to_table, compose->account->address,
1547                                     GINT_TO_POINTER(1));
1548
1549         /* remove address on To: and that of current account */
1550         for (cur = cc_list; cur != NULL; ) {
1551                 GSList *next = cur->next;
1552
1553                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1554                         cc_list = g_slist_remove(cc_list, cur->data);
1555                 else
1556                         g_hash_table_insert(to_table, cur->data, cur);
1557
1558                 cur = next;
1559         }
1560         g_hash_table_destroy(to_table);
1561         g_free(from);
1562
1563         if (cc_list) {
1564                 for (cur = cc_list; cur != NULL; cur = cur->next)
1565                         compose_entry_append(compose, (gchar *)cur->data,
1566                                              COMPOSE_CC);
1567                 slist_free_strings(cc_list);
1568                 g_slist_free(cc_list);
1569         }
1570 }
1571
1572 #define SET_ENTRY(entry, str) \
1573 { \
1574         if (str && *str) \
1575                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1576 }
1577
1578 #define SET_ADDRESS(type, str) \
1579 { \
1580         if (str && *str) \
1581                 compose_entry_append(compose, str, type); \
1582 }
1583
1584 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1585 {
1586         g_return_if_fail(msginfo != NULL);
1587
1588         SET_ENTRY(subject_entry, msginfo->subject);
1589         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1590         SET_ADDRESS(COMPOSE_CC, compose->cc);
1591         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1592         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1593
1594 #if 0 /* NEW COMPOSE GUI */
1595         if (compose->bcc) {
1596                 GtkItemFactory *ifactory;
1597                 GtkWidget *menuitem;
1598
1599                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1600                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
1601                 gtk_check_menu_item_set_active
1602                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1603         }
1604         if (compose->replyto) {
1605                 GtkItemFactory *ifactory;
1606                 GtkWidget *menuitem;
1607
1608                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1609                 menuitem = gtk_item_factory_get_item
1610                         (ifactory, "/Message/Reply to");
1611                 gtk_check_menu_item_set_active
1612                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1613         }
1614 #endif
1615 }
1616
1617 #undef SET_ENTRY
1618 #undef SET_ADDRESS
1619
1620 static void compose_exec_sig(Compose *compose, gchar *sigfile)
1621 {
1622         FILE *tmpfp;
1623         pid_t thepid;
1624         gchar *sigtext;
1625         FILE  *sigprg;
1626         gchar  *buf;
1627         size_t buf_len = 128;
1628  
1629         if (strlen(sigfile) < 2)
1630           return;
1631  
1632         sigprg = popen(sigfile+1, "r");
1633         if (sigprg) {
1634
1635                 buf = g_malloc(buf_len);
1636
1637                 if (!buf) {
1638                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1639                         "Unable to insert signature (malloc failed)\n", -1);
1640
1641                         pclose(sigprg);
1642                         return;
1643                 }
1644
1645                 while (!feof(sigprg)) {
1646                         bzero(buf, buf_len);
1647                         fread(buf, buf_len-1, 1, sigprg);
1648                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, buf, -1);
1649                 }
1650
1651                 g_free(buf);
1652                 pclose(sigprg);
1653         }
1654         else
1655         {
1656                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1657                 "Can't exec file: ", -1);
1658                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1659                 sigfile+1, -1);
1660         }
1661 }
1662
1663 static void compose_insert_sig(Compose *compose)
1664 {
1665         gchar *sigfile;
1666
1667         if (compose->account && compose->account->sig_path)
1668                 sigfile = g_strdup(compose->account->sig_path);
1669         else {
1670                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1671                                       DEFAULT_SIGNATURE, NULL);
1672         }
1673
1674         if (!is_file_or_fifo_exist(sigfile) & (sigfile[0] != '|')) {
1675                 g_free(sigfile);
1676                 return;
1677         }
1678
1679         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1680         if (prefs_common.sig_sep) {
1681                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1682                                 prefs_common.sig_sep, -1);
1683                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1684                                 "\n", 1);
1685         }
1686
1687         if (sigfile[0] == '|')
1688         {
1689                 compose_exec_sig(compose, sigfile);
1690         }
1691         else
1692         {
1693                 compose_insert_file(compose, sigfile);
1694         }
1695         g_free(sigfile);
1696 }
1697
1698 static void compose_insert_file(Compose *compose, const gchar *file)
1699 {
1700         GtkSText *text = GTK_STEXT(compose->text);
1701         gchar buf[BUFFSIZE];
1702         gint len;
1703         FILE *fp;
1704
1705         g_return_if_fail(file != NULL);
1706
1707         if ((fp = fopen(file, "r")) == NULL) {
1708                 FILE_OP_ERROR(file, "fopen");
1709                 return;
1710         }
1711
1712         gtk_stext_freeze(text);
1713
1714         while (fgets(buf, sizeof(buf), fp) != NULL) {
1715                 /* Strip <CR> if DOS/Windoze file, replace <CR> with <LF> if MAC file */
1716                 len = strlen(buf);
1717                 if (len > 1 && buf[len - 2] == '\r' && buf[len - 1] == '\n') {
1718                         buf[len - 2] = '\n';
1719                         buf[len - 1] = '\0';
1720                 } else {
1721                         while (--len > 0)
1722                                 if (buf[len] == '\r')
1723                                         buf[len] = '\n';
1724                 }
1725
1726                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1727         }
1728
1729         gtk_stext_thaw(text);
1730
1731         fclose(fp);
1732 }
1733
1734 static void compose_attach_info(Compose * compose, AttachInfo * ainfo,
1735                                 ContentType cnttype)
1736 {
1737         gchar *text[N_ATTACH_COLS];
1738         gint row;
1739
1740         text[COL_MIMETYPE] = ainfo->content_type;
1741         text[COL_SIZE] = to_human_readable(ainfo->size);
1742         text[COL_NAME] = ainfo->name;
1743
1744         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1745         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1746
1747         if (cnttype != MIME_MESSAGE_RFC822)
1748                 compose_changed_cb(NULL, compose);
1749 }
1750
1751 static void compose_attach_append_with_type(Compose *compose,
1752                                             const gchar *file,
1753                                             const gchar *type,
1754                                             ContentType cnttype)
1755 {
1756         AttachInfo *ainfo;
1757         off_t size;
1758
1759         if (!is_file_exist(file)) {
1760                 g_warning(_("File %s doesn't exist\n"), file);
1761                 return;
1762         }
1763         if ((size = get_file_size(file)) < 0) {
1764                 g_warning(_("Can't get file size of %s\n"), file);
1765                 return;
1766         }
1767         if (size == 0) {
1768                 alertpanel_notice(_("File %s is empty\n"), file);
1769                 return;
1770         }
1771 #if 0 /* NEW COMPOSE GUI */
1772         if (!compose->use_attach) {
1773                 GtkItemFactory *ifactory;
1774                 GtkWidget *menuitem;
1775
1776                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1777                 menuitem = gtk_item_factory_get_item(ifactory,
1778                                                      "/Message/Attach");
1779                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1780                                                TRUE);
1781         }
1782 #endif
1783         ainfo = g_new0(AttachInfo, 1);
1784         ainfo->file = g_strdup(file);
1785
1786         if (cnttype == MIME_MESSAGE_RFC822) {
1787                 ainfo->encoding = ENC_7BIT;
1788                 ainfo->name = g_strdup_printf(_("Message: %s"),
1789                                               g_basename(file));
1790         } else {
1791                 ainfo->encoding = ENC_BASE64;
1792                 ainfo->name = g_strdup(g_basename(file));
1793         }
1794
1795         ainfo->content_type = g_strdup(type);
1796         ainfo->size = size;
1797
1798         compose_attach_info(compose, ainfo, cnttype);
1799 }
1800
1801 static void compose_attach_append(Compose *compose, const gchar *file,
1802                                   ContentType cnttype)
1803 {
1804         AttachInfo *ainfo;
1805         gchar *text[N_ATTACH_COLS];
1806         off_t size;
1807         gint row;
1808
1809         if (!is_file_exist(file)) {
1810                 g_warning(_("File %s doesn't exist\n"), file);
1811                 return;
1812         }
1813         if ((size = get_file_size(file)) < 0) {
1814                 g_warning(_("Can't get file size of %s\n"), file);
1815                 return;
1816         }
1817         if (size == 0) {
1818                 alertpanel_notice(_("File %s is empty\n"), file);
1819                 return;
1820         }
1821 #if 0 /* NEW COMPOSE GUI */
1822         if (!compose->use_attach) {
1823                 GtkItemFactory *ifactory;
1824                 GtkWidget *menuitem;
1825
1826                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1827                 menuitem = gtk_item_factory_get_item(ifactory,
1828                                                      "/Message/Attach");
1829                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1830                                                TRUE);
1831         }
1832 #endif
1833         ainfo = g_new0(AttachInfo, 1);
1834         ainfo->file = g_strdup(file);
1835
1836         if (cnttype == MIME_MESSAGE_RFC822) {
1837                 ainfo->content_type = g_strdup("message/rfc822");
1838                 ainfo->encoding = ENC_7BIT;
1839                 ainfo->name = g_strdup_printf(_("Message: %s"),
1840                                               g_basename(file));
1841         } else {
1842                 ainfo->content_type = procmime_get_mime_type(file);
1843                 if (!ainfo->content_type)
1844                         ainfo->content_type =
1845                                 g_strdup("application/octet-stream");
1846                 ainfo->encoding = ENC_BASE64;
1847                 ainfo->name = g_strdup(g_basename(file));
1848         }
1849         ainfo->size = size;
1850
1851         compose_attach_info(compose, ainfo, cnttype);
1852 }
1853
1854 static void compose_wrap_line(Compose *compose)
1855 {
1856         GtkSText *text = GTK_STEXT(compose->text);
1857         gint ch_len, last_ch_len;
1858         gchar cbuf[MB_LEN_MAX], last_ch;
1859         guint text_len;
1860         guint line_end;
1861         guint quoted;
1862         gint p_start, p_end;
1863         gint line_pos, cur_pos;
1864         gint line_len, cur_len;
1865
1866 #define GET_STEXT(pos)                                                        \
1867         if (text->use_wchar)                                                 \
1868                 ch_len = wctomb(cbuf, (wchar_t)GTK_STEXT_INDEX(text, (pos))); \
1869         else {                                                               \
1870                 cbuf[0] = GTK_STEXT_INDEX(text, (pos));                       \
1871                 ch_len = 1;                                                  \
1872         }
1873
1874         gtk_stext_freeze(text);
1875
1876         text_len = gtk_stext_get_length(text);
1877
1878         /* check to see if the point is on the paragraph mark (empty line). */
1879         cur_pos = gtk_stext_get_point(text);
1880         GET_STEXT(cur_pos);
1881         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
1882                 if (cur_pos == 0)
1883                         goto compose_end; /* on the paragraph mark */
1884                 GET_STEXT(cur_pos - 1);
1885                 if (ch_len == 1 && *cbuf == '\n')
1886                         goto compose_end; /* on the paragraph mark */
1887         }
1888
1889         /* find paragraph start. */
1890         line_end = quoted = 0;
1891         for (p_start = cur_pos; p_start >= 0; --p_start) {
1892                 GET_STEXT(p_start);
1893                 if (ch_len == 1 && *cbuf == '\n') {
1894                         if (quoted)
1895                                 goto compose_end; /* quoted part */
1896                         if (line_end) {
1897                                 p_start += 2;
1898                                 break;
1899                         }
1900                         line_end = 1;
1901                 } else {
1902                         if (ch_len == 1 && strchr(">:#", *cbuf))
1903                                 quoted = 1;
1904                         else if (ch_len != 1 || !isspace(*cbuf))
1905                                 quoted = 0;
1906
1907                         line_end = 0;
1908                 }
1909         }
1910         if (p_start < 0)
1911                 p_start = 0;
1912
1913         /* find paragraph end. */
1914         line_end = 0;
1915         for (p_end = cur_pos; p_end < text_len; p_end++) {
1916                 GET_STEXT(p_end);
1917                 if (ch_len == 1 && *cbuf == '\n') {
1918                         if (line_end) {
1919                                 p_end -= 1;
1920                                 break;
1921                         }
1922                         line_end = 1;
1923                 } else {
1924                         if (line_end && ch_len == 1 && strchr(">:#", *cbuf))
1925                                 goto compose_end; /* quoted part */
1926
1927                         line_end = 0;
1928                 }
1929         }
1930         if (p_end >= text_len)
1931                 p_end = text_len;
1932
1933         if (p_start >= p_end)
1934                 goto compose_end;
1935
1936         line_len = cur_len = 0;
1937         last_ch_len = 0;
1938         last_ch = '\0';
1939         line_pos = p_start;
1940         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
1941                 guint space = 0;
1942
1943                 GET_STEXT(cur_pos);
1944
1945                 if (ch_len < 0) {
1946                         cbuf[0] = '\0';
1947                         ch_len = 1;
1948                 }
1949
1950                 if (ch_len == 1 && isspace(*cbuf))
1951                         space = 1;
1952
1953                 if (ch_len == 1 && *cbuf == '\n') {
1954                         guint replace = 0;
1955                         if (last_ch_len == 1 && !isspace(last_ch)) {
1956                                 if (cur_pos + 1 < p_end) {
1957                                         GET_STEXT(cur_pos + 1);
1958                                         if (ch_len == 1 && !isspace(*cbuf))
1959                                                 replace = 1;
1960                                 }
1961                         }
1962                         gtk_stext_set_point(text, cur_pos + 1);
1963                         gtk_stext_backward_delete(text, 1);
1964                         if (replace) {
1965                                 gtk_stext_set_point(text, cur_pos);
1966                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
1967                                 space = 1;
1968                         }
1969                         else {
1970                                 p_end--;
1971                                 cur_pos--;
1972                                 continue;
1973                         }
1974                 }
1975
1976                 last_ch_len = ch_len;
1977                 last_ch = *cbuf;
1978
1979                 if (space) {
1980                         line_pos = cur_pos + 1;
1981                         line_len = cur_len + ch_len;
1982                 }
1983
1984                 if (cur_len + ch_len > prefs_common.linewrap_len &&
1985                     line_len > 0) {
1986                         gint tlen = ch_len;
1987
1988                         GET_STEXT(line_pos - 1);
1989                         if (ch_len == 1 && isspace(*cbuf)) {
1990                                 gtk_stext_set_point(text, line_pos);
1991                                 gtk_stext_backward_delete(text, 1);
1992                                 p_end--;
1993                                 cur_pos--;
1994                                 line_pos--;
1995                                 cur_len--;
1996                                 line_len--;
1997                         }
1998                         ch_len = tlen;
1999
2000                         gtk_stext_set_point(text, line_pos);
2001                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2002                         p_end++;
2003                         cur_pos++;
2004                         line_pos++;
2005                         cur_len = cur_len - line_len + ch_len;
2006                         line_len = 0;
2007                         continue;
2008                 }
2009
2010                 if (ch_len > 1) {
2011                         line_pos = cur_pos + 1;
2012                         line_len = cur_len + ch_len;
2013                 }
2014                 cur_len += ch_len;
2015         }
2016
2017 compose_end:
2018         gtk_stext_thaw(text);
2019
2020 #undef GET_STEXT
2021 }
2022
2023 /* return indent length */
2024 static guint get_indent_length(GtkSText *text, guint start_pos,
2025                                guint text_len) {
2026         gint indent_len = 0;
2027         gint i, ch_len;
2028         gchar cbuf[MB_CUR_MAX];
2029
2030         for (i = start_pos; i < text_len; i++) {
2031                 if (text->use_wchar)
2032                         ch_len = wctomb
2033                                 (cbuf, (wchar_t)GTK_STEXT_INDEX(text, i));
2034                 else {
2035                         cbuf[0] = GTK_STEXT_INDEX(text, i);
2036                         ch_len = 1;
2037                 }
2038                 if (ch_len > 1)
2039                         break;
2040                 /* allow space, tab, > or | */
2041                 if (cbuf[0] != ' ' && cbuf[0] != '\t' &&
2042                     cbuf[0] != '>' && cbuf[0] != '|')
2043                         break;
2044                 indent_len++;
2045         }
2046
2047         return indent_len;
2048 }
2049
2050 /* insert quotation string when line was wrapped, we know these
2051    are single byte characters */
2052 static guint ins_quote(GtkSText *text, guint quote_len, guint indent_len,
2053                        guint prev_line_pos, guint text_len,
2054                        gchar *quote_fmt) {
2055         guint i, ins_len;
2056         gchar ch;
2057
2058         if (indent_len) {
2059                 for (i = 0; i < indent_len; i++) {
2060                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2061                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2062                 }
2063                 ins_len = indent_len;
2064         }
2065         else {
2066                 gtk_stext_insert(text, NULL, NULL, NULL, quote_fmt, quote_len);
2067                 ins_len = quote_len;
2068         }
2069
2070         return ins_len;
2071 }
2072
2073 #undef WRAP_DEBUG
2074 #ifdef WRAP_DEBUG
2075 /* Darko: used when I debug wrapping */
2076 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2077 {
2078     int i;
2079     char ch;
2080
2081     printf("%d [", pos);
2082     for (i = pos; i < tlen; i++)
2083     {
2084         ch = GTK_STEXT_INDEX(text, i);
2085         if (breakoncr && ch == '\n')
2086             break;
2087         printf("%c", ch);
2088     }
2089     printf("]\n");
2090 }
2091 #endif
2092
2093 static void compose_wrap_line_all(Compose *compose)
2094 {
2095         GtkSText *text = GTK_STEXT(compose->text);
2096         guint tlen;
2097         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2098         gint line_len = 0, cur_len = 0;
2099         gint ch_len;
2100         gint is_new_line = 1, do_delete = 0;
2101         guint qlen = 0, i_len = 0;
2102         guint linewrap_quote = prefs_common.linewrap_quote;
2103         guint linewrap_len = prefs_common.linewrap_len;
2104         gchar *qfmt = prefs_common.quotemark;
2105         gchar cbuf[MB_LEN_MAX];
2106
2107         gtk_stext_freeze(text);
2108
2109         /* make text buffer contiguous */
2110         gtk_stext_compact_buffer(text);
2111
2112         tlen = gtk_stext_get_length(text);
2113
2114         for (; cur_pos < tlen; cur_pos++) {
2115                 /* mark position of new line - needed for quotation wrap */
2116                 if (linewrap_quote && is_new_line) {
2117                         qlen = gtkstext_str_strcmp(text, cur_pos, tlen, qfmt);
2118                         is_new_line = 0;
2119                         if (qlen) {
2120                                 i_len = get_indent_length(text, cur_pos, tlen);
2121                         }
2122                         else
2123                                 i_len = 0;
2124                         p_pos = cur_pos;
2125 #ifdef WRAP_DEBUG
2126                         printf("new line i_len=%d qlen=%d p_pos=", i_len, qlen);
2127                         dump_text(text, p_pos, tlen, 1);
2128 #endif
2129                 }
2130
2131                 /* get character(s) at current position */
2132                 if (text->use_wchar)
2133                         ch_len = wctomb
2134                                 (cbuf, (wchar_t)GTK_STEXT_INDEX(text, cur_pos));
2135                 else {
2136                         cbuf[0] = GTK_STEXT_INDEX(text, cur_pos);
2137                         ch_len = 1;
2138                 }
2139
2140                 /* fix line length for tabs */
2141                 if (ch_len == 1 && *cbuf == '\t') {
2142                         guint tab_width = text->default_tab_width;
2143                         guint tab_offset = line_len % tab_width;
2144
2145 #ifdef WRAP_DEBUG
2146                         printf("found tab at pos=%d line_len=%d ", cur_pos,
2147                                 line_len);
2148 #endif
2149                         if (tab_offset) {
2150                                 line_len += tab_width - tab_offset - 1;
2151                                 cur_len = line_len;
2152                         }
2153 #ifdef WRAP_DEBUG
2154                         printf("new_len=%d\n", line_len);
2155 #endif
2156                 }
2157
2158                 /* we have encountered line break */
2159                 if (ch_len == 1 && *cbuf == '\n') {
2160                         gint clen;
2161                         guint ilen;
2162                         gchar cb[MB_CUR_MAX];
2163
2164 #ifdef WRAP_DEBUG
2165                         printf("found CR at %d\n", cur_pos);
2166 #endif
2167                         /* if it's just quotation + newline skip it */
2168                         if (i_len && (cur_pos + 1 < tlen)) {
2169                                 /* check if text at new line matches indent */
2170                                 ilen =  gtkstext_strncmp(text, cur_pos + 1,
2171                                                          p_pos, i_len, tlen);
2172                                 if (cur_pos + ilen < tlen) {
2173                                         if (text->use_wchar)
2174                                                 clen = wctomb(cb, (wchar_t)GTK_STEXT_INDEX(text, cur_pos + ilen + 1));
2175                                         else {
2176                                                 cb[0] = GTK_STEXT_INDEX(text,
2177                                                             cur_pos + ilen + 1);
2178                                                 clen = 1;
2179                                         }
2180                                         /* no need to join the lines */
2181                                         if ((clen == 1) && (cb[0] == '\n'))
2182                                                 do_delete = 0;
2183                                 }
2184                         }
2185
2186 #ifdef WRAP_DEBUG
2187                         printf("qlen=%d l_len=%d wrap_len=%d do_del=%d\n",
2188                                 qlen, line_len, linewrap_len, do_delete);
2189 #endif
2190                         /* should we delete to perform smart wrapping */
2191                         if (qlen && line_len < linewrap_len && do_delete) {
2192                                 /* get rid of newline */
2193                                 gtk_stext_set_point(text, cur_pos);
2194                                 gtk_stext_forward_delete(text, 1);
2195                                 tlen--;
2196
2197                                 /* if text starts with quote fmt or with
2198                                    indent string, delete them */
2199                                 if (i_len) {
2200                                         ilen =  gtkstext_strncmp(text, cur_pos,
2201                                                                  p_pos, i_len,
2202                                                                  tlen);
2203                                         if (ilen) {
2204                                                 gtk_stext_forward_delete(text,
2205                                                                          ilen);
2206                                                 tlen -= ilen;
2207                                         }
2208                                 }
2209                                 else if (qlen) {
2210                                         if (gtkstext_str_strcmp(text, cur_pos,
2211                                                                 tlen, qfmt)) {
2212                                                 gtk_stext_forward_delete(text,
2213                                                                  qlen);
2214                                                 tlen -= qlen;
2215                                         }
2216                                 }
2217
2218                                 if (text->use_wchar)
2219                                         clen = wctomb
2220                                                 (cb, (wchar_t)GTK_STEXT_INDEX(text, cur_pos));
2221                                 else {
2222                                         cb[0] = GTK_STEXT_INDEX(text, cur_pos);
2223                                         clen = 1;
2224                                 }
2225
2226                                 /* insert space if it's alphanumeric */
2227                                 if ((cur_pos != line_pos) &&
2228                                     ((clen > 1) || isalnum(cb[0]))) {
2229                                         gtk_stext_insert(text, NULL, NULL,
2230                                                          NULL, " ", 1);
2231                                         gtk_stext_compact_buffer(text);
2232                                         tlen++;
2233                                 }
2234
2235                                 /* and start over with current line */
2236                                 cur_pos = p_pos - 1;
2237                                 line_pos = cur_pos;
2238                                 line_len = cur_len = 0;
2239                                 qlen = 0;
2240                                 do_delete = 0;
2241                                 is_new_line = 1;
2242 #ifdef WRAP_DEBUG
2243                                 printf("after delete l_pos=");
2244                                 dump_text(text, line_pos, tlen, 1);
2245 #endif
2246                                 continue;
2247                         }
2248
2249                         /* mark new line beginning */
2250                         line_pos = cur_pos + 1;
2251                         line_len = cur_len = 0;
2252                         qlen = 0;
2253                         do_delete = 0;
2254                         is_new_line = 1;
2255                         continue;
2256                 }
2257
2258                 if (ch_len < 0) {
2259                         cbuf[0] = '\0';
2260                         ch_len = 1;
2261                 }
2262
2263                 /* possible line break */
2264                 if (ch_len == 1 && isspace(*cbuf)) {
2265                         line_pos = cur_pos + 1;
2266                         line_len = cur_len + ch_len;
2267                 }
2268
2269                 /* are we over wrapping length set in preferences ? */
2270                 if (cur_len + ch_len > linewrap_len) {
2271                         gint clen;
2272
2273 #ifdef WRAP_DEBUG
2274                         printf("should wrap cur_pos=%d ", cur_pos);
2275                         dump_text(text, p_pos, tlen, 1);
2276                         dump_text(text, line_pos, tlen, 1);
2277 #endif
2278                         /* force wrapping if it is one long word but not URL */
2279                         if (p_pos + i_len == line_pos)
2280                                 if (!is_url_string(text, line_pos, tlen))
2281                                         line_pos = cur_pos - 1;
2282 #ifdef WRAP_DEBUG
2283                         printf("new line_pos=%d\n", line_pos);
2284 #endif
2285
2286                         /* if next character is space delete it */
2287                         if (text->use_wchar)
2288                                 clen = wctomb(cbuf, (wchar_t)GTK_STEXT_INDEX(text, line_pos - 1));
2289                         else {
2290                                 cbuf[0] = GTK_STEXT_INDEX(text, line_pos - 1);
2291                                 clen = 1;
2292                         }
2293                         if (clen == 1 && isspace(*cbuf)) {
2294                                 if (p_pos + i_len != line_pos ||
2295                                     !is_url_string(text, line_pos, tlen)) {
2296                                         gtk_stext_set_point(text, line_pos);
2297                                         gtk_stext_backward_delete(text, 1);
2298                                         tlen--;
2299                                         cur_pos--;
2300                                         line_pos--;
2301                                         cur_len--;
2302                                         line_len--;
2303                                 }
2304                         }
2305
2306                         /* if it is URL at beginning of line don't wrap */
2307                         if (p_pos + i_len == line_pos &&
2308                             is_url_string(text, line_pos, tlen)) {
2309 #ifdef WRAP_DEBUG
2310                                 printf("found URL at ");
2311                                 dump_text(text, line_pos, tlen, 1);
2312 #endif
2313                                 continue;
2314                         }
2315
2316                         /* insert CR */
2317                         gtk_stext_set_point(text, line_pos);
2318                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2319                         gtk_stext_compact_buffer(text);
2320                         tlen++;
2321                         cur_pos++;
2322                         line_pos++;
2323                         cur_len = cur_len - line_len + ch_len;
2324                         line_len = 0;
2325 #ifdef WRAP_DEBUG
2326                         printf("after CR insert ");
2327                         dump_text(text, line_pos, tlen, 1);
2328 #endif
2329
2330                         /* should we insert quotation ? */
2331                         if (linewrap_quote && qlen) {
2332                                 /* only if line is not already quoted  */
2333                                 if (!gtkstext_str_strcmp(text, line_pos,
2334                                                          tlen, qfmt)) {
2335                                         guint ins_len;
2336
2337                                         if (line_pos - p_pos > i_len) {
2338                                                 ins_len = ins_quote(text,
2339                                                                     qlen,
2340                                                                     i_len,
2341                                                                     p_pos,
2342                                                                     tlen,
2343                                                                     qfmt);
2344
2345                                                 gtk_stext_compact_buffer(text);
2346                                                 tlen += ins_len;
2347                                         }
2348
2349                                         /* for loop will increase it */
2350                                         cur_pos = line_pos - 1;
2351                                         cur_len = 0;
2352                                         line_len = 0;
2353                                         /* start over with current line */
2354                                         is_new_line = 1;
2355                                         do_delete = 1;
2356 #ifdef WRAP_DEBUG
2357                                         printf("after quote insert ");
2358                                         dump_text(text, line_pos, tlen, 1);
2359 #endif
2360                                 }
2361                         }
2362                         continue;
2363                 }
2364
2365                 if (ch_len > 1) {
2366                         line_pos = cur_pos + 1;
2367                         line_len = cur_len + ch_len;
2368                 }
2369                 /* advance to next character in buffer */
2370                 cur_len += ch_len;
2371         }
2372
2373         gtk_stext_thaw(text);
2374 }
2375
2376 static void compose_set_title(Compose *compose)
2377 {
2378         gchar *str;
2379         gchar *edited;
2380
2381         edited = compose->modified ? _(" [Edited]") : "";
2382         if (compose->account && compose->account->address)
2383                 str = g_strdup_printf(_("%s - Compose message%s"),
2384                                       compose->account->address, edited);
2385         else
2386                 str = g_strdup_printf(_("Compose message%s"), edited);
2387         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2388         g_free(str);
2389 }
2390
2391 /**
2392  * compose_current_mail_account:
2393  * 
2394  * Find a current mail account (the currently selected account, or the
2395  * default account, if a news account is currently selected).  If a
2396  * mail account cannot be found, display an error message.
2397  * 
2398  * Return value: Mail account, or NULL if not found.
2399  **/
2400 static PrefsAccount *
2401 compose_current_mail_account(void)
2402 {
2403         PrefsAccount *ac;
2404
2405         if (cur_account && cur_account->protocol != A_NNTP)
2406                 ac = cur_account;
2407         else {
2408                 ac = account_get_default();
2409                 if (!ac || ac->protocol == A_NNTP) {
2410                         alertpanel_error(_("Account for sending mail is not specified.\n"
2411                                            "Please select a mail account before sending."));
2412                         return NULL;
2413                 }
2414         }
2415         return ac;
2416 }
2417
2418 gboolean compose_check_for_valid_recipient(Compose *compose) {
2419         gchar *recipient_headers[] = {"To:", "Newsgroups:", "Cc:", "Bcc:", NULL};
2420         gboolean recipient_found = FALSE;
2421         GSList *list;
2422         gchar **strptr;
2423
2424         for(list = compose->header_list; list; list = list->next) {
2425                 gchar *header;
2426                 gchar *entry;
2427                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(((compose_headerentry *)list->data)->combo)->entry));
2428                 entry = gtk_editable_get_chars(GTK_EDITABLE(((compose_headerentry *)list->data)->entry), 0, -1);
2429                 g_strstrip(entry);
2430                 if(entry[0] != '\0') {
2431                         for(strptr = recipient_headers; *strptr != NULL; strptr++) {
2432                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2433                                         recipient_found = TRUE;
2434                                 }
2435                         }
2436                 }
2437                 g_free(entry);
2438         }
2439         return recipient_found;
2440 }
2441
2442 gint compose_send(Compose *compose)
2443 {
2444         gchar tmp[MAXPATHLEN + 1];
2445         gint ok = 0;
2446         static gboolean lock = FALSE;
2447
2448         if (lock) return 1;
2449
2450         g_return_val_if_fail(compose->account != NULL, -1);
2451         g_return_val_if_fail(compose->orig_account != NULL, -1);
2452
2453         lock = TRUE;
2454
2455         if(!compose_check_for_valid_recipient(compose)) {
2456                 alertpanel_error(_("Recipient is not specified."));
2457                 lock = FALSE;
2458                 return 1;
2459         }
2460
2461         /* write to temporary file */
2462         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
2463                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
2464
2465         if (prefs_common.linewrap_at_send)
2466                 compose_wrap_line_all(compose);
2467
2468         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2469                 lock = FALSE;
2470                 return -1;
2471         }
2472
2473         if (!compose->to_list && !compose->newsgroup_list) {
2474                 g_warning(_("can't get recipient list."));
2475                 unlink(tmp);
2476                 lock = FALSE;
2477                 return -1;
2478         }
2479
2480         if (compose->to_list) {
2481                 PrefsAccount *ac;
2482
2483 #if 0 /* NEW COMPOSE GUI */
2484                 if (compose->account->protocol != A_NNTP)
2485                         ac = compose->account;
2486                 else if (compose->orig_account->protocol != A_NNTP)
2487                         ac = compose->orig_account;
2488                 else if (cur_account && cur_account->protocol != A_NNTP)
2489                         ac = cur_account;
2490                 else {
2491                         ac = compose_current_mail_account();
2492                         if (!ac) {
2493                                 unlink(tmp);
2494                                 lock = FALSE;
2495                                 return -1;
2496                         }
2497                 }
2498 #endif
2499                 ac = compose->account;
2500
2501                 ok = send_message(tmp, ac, compose->to_list);
2502                 statusbar_pop_all();
2503         }
2504
2505         if (ok == 0 && compose->newsgroup_list) {
2506                 Folder *folder;
2507
2508                 if (compose->account->protocol == A_NNTP)
2509                         folder = FOLDER(compose->account->folder);
2510                 else
2511                         folder = FOLDER(compose->orig_account->folder);
2512
2513                 ok = news_post(folder, tmp);
2514                 if (ok < 0) {
2515                         alertpanel_error(_("Error occurred while posting the message to %s ."),
2516                                          compose->account->nntp_server);
2517                         unlink(tmp);
2518                         lock = FALSE;
2519                         return -1;
2520                 }
2521         }
2522
2523         /* queue message if failed to send */
2524         if (ok < 0) {
2525                 if (prefs_common.queue_msg) {
2526                         AlertValue val;
2527
2528                         val = alertpanel
2529                                 (_("Queueing"),
2530                                  _("Error occurred while sending the message.\n"
2531                                    "Put this message into queue folder?"),
2532                                  _("OK"), _("Cancel"), NULL);
2533                         if (G_ALERTDEFAULT == val) {
2534                                 ok = compose_queue(compose, tmp);
2535                                 if (ok < 0)
2536                                         alertpanel_error(_("Can't queue the message."));
2537                         }
2538                 } else
2539                         alertpanel_error(_("Error occurred while sending the message."));
2540         } else {
2541                 if (compose->mode == COMPOSE_REEDIT) {
2542                         compose_remove_reedit_target(compose);
2543                         if (compose->targetinfo)
2544                                 folderview_update_item
2545                                         (compose->targetinfo->folder, TRUE);
2546                 }
2547         }
2548
2549         /* save message to outbox */
2550         if (ok == 0 && prefs_common.savemsg) {
2551                 if (compose_save_to_outbox(compose, tmp) < 0)
2552                         alertpanel_error
2553                                 (_("Can't save the message to outbox."));
2554         }
2555
2556         unlink(tmp);
2557         lock = FALSE;
2558         return ok;
2559 }
2560
2561 static gboolean compose_use_attach(Compose *compose) {
2562     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
2563 }
2564
2565 static gint compose_write_to_file(Compose *compose, const gchar *file,
2566                                   gboolean is_draft)
2567 {
2568         FILE *fp;
2569         size_t len;
2570         gchar *chars;
2571         gchar *buf;
2572         const gchar *out_codeset;
2573         EncodingType encoding;
2574
2575         if ((fp = fopen(file, "w")) == NULL) {
2576                 FILE_OP_ERROR(file, "fopen");
2577                 return -1;
2578         }
2579
2580         /* chmod for security */
2581         if (change_file_mode_rw(fp, file) < 0) {
2582                 FILE_OP_ERROR(file, "chmod");
2583                 g_warning(_("can't change file mode\n"));
2584         }
2585
2586         /* get all composed text */
2587         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2588         len = strlen(chars);
2589         if (is_ascii_str(chars)) {
2590                 buf = g_strdup(chars);
2591                 out_codeset = CS_US_ASCII;
2592                 encoding = ENC_7BIT;
2593         } else {
2594                 const gchar *src_codeset;
2595
2596                 out_codeset = conv_get_outgoing_charset_str();
2597                 if (!strcasecmp(out_codeset, CS_US_ASCII))
2598                         out_codeset = CS_ISO_8859_1;
2599                 encoding = procmime_get_encoding_for_charset(out_codeset);
2600
2601                 src_codeset = conv_get_current_charset_str();
2602                 /* if current encoding is US-ASCII, set it the same as
2603                    outgoing one to prevent code conversion failure */
2604                 if (!strcasecmp(src_codeset, CS_US_ASCII))
2605                         src_codeset = out_codeset;
2606
2607                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
2608                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
2609
2610                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
2611                 if (!buf) {
2612                         g_free(chars);
2613                         fclose(fp);
2614                         unlink(file);
2615                         alertpanel_error(_("Can't convert the codeset of the message."));
2616                         return -1;
2617                 }
2618         }
2619         g_free(chars);
2620
2621         /* write headers */
2622         if (compose_write_headers
2623                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
2624                 g_warning(_("can't write headers\n"));
2625                 fclose(fp);
2626                 /* unlink(file); */
2627                 g_free(buf);
2628                 return -1;
2629         }
2630
2631         if (compose_use_attach(compose)) {
2632 #if USE_GPGME
2633             /* This prolog message is ignored by mime software and
2634              * because it would make our signing/encryption task
2635              * tougher, we don't emit it in that case */
2636             if (!compose->use_signing && !compose->use_encryption)
2637 #endif
2638                 fputs("This is a multi-part message in MIME format.\n", fp);
2639
2640                 fprintf(fp, "\n--%s\n", compose->boundary);
2641                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
2642                         out_codeset);
2643                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
2644                         procmime_get_encoding_str(encoding));
2645                 fputc('\n', fp);
2646         }
2647
2648         /* write body */
2649         len = strlen(buf);
2650         if (encoding == ENC_BASE64) {
2651                 gchar outbuf[B64_BUFFSIZE];
2652                 gint i, l;
2653
2654                 for (i = 0; i < len; i += B64_LINE_SIZE) {
2655                         l = MIN(B64_LINE_SIZE, len - i);
2656                         to64frombits(outbuf, buf + i, l);
2657                         fputs(outbuf, fp);
2658                         fputc('\n', fp);
2659                 }
2660         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
2661                 FILE_OP_ERROR(file, "fwrite");
2662                 fclose(fp);
2663                 unlink(file);
2664                 g_free(buf);
2665                 return -1;
2666         }
2667         g_free(buf);
2668
2669         if (compose_use_attach(compose))
2670                 compose_write_attach(compose, fp);
2671
2672         if (fclose(fp) == EOF) {
2673                 FILE_OP_ERROR(file, "fclose");
2674                 unlink(file);
2675                 return -1;
2676         }
2677
2678 #if USE_GPGME
2679         if (compose->use_signing) {
2680                 if (rfc2015_sign(file, compose->account) < 0) {
2681                         unlink(file);
2682                         return -1;
2683                 }
2684         }
2685         if (compose->use_encryption) {
2686                 if (rfc2015_encrypt(file, compose->to_list) < 0) {
2687                         unlink(file);
2688                         return -1;
2689                 }
2690         }
2691 #endif /* USE_GPGME */
2692
2693         return 0;
2694 }
2695
2696 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
2697 {
2698         FILE *fp;
2699         size_t len;
2700         gchar *chars;
2701
2702         if ((fp = fopen(file, "w")) == NULL) {
2703                 FILE_OP_ERROR(file, "fopen");
2704                 return -1;
2705         }
2706
2707         /* chmod for security */
2708         if (change_file_mode_rw(fp, file) < 0) {
2709                 FILE_OP_ERROR(file, "chmod");
2710                 g_warning(_("can't change file mode\n"));
2711         }
2712
2713         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2714
2715         /* write body */
2716         len = strlen(chars);
2717         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
2718                 FILE_OP_ERROR(file, "fwrite");
2719                 g_free(chars);
2720                 fclose(fp);
2721                 unlink(file);
2722                 return -1;
2723         }
2724
2725         g_free(chars);
2726
2727         if (fclose(fp) == EOF) {
2728                 FILE_OP_ERROR(file, "fclose");
2729                 unlink(file);
2730                 return -1;
2731         }
2732         return 0;
2733 }
2734
2735 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
2736 {
2737         FolderItem *outbox;
2738         gchar *path;
2739         gint num;
2740         FILE *fp;
2741
2742         debug_print(_("saving sent message...\n"));
2743
2744         outbox = folder_get_default_outbox();
2745         path = folder_item_get_path(outbox);
2746         if (!is_dir_exist(path))
2747                 make_dir_hier(path);
2748
2749         folder_item_scan(outbox);
2750         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
2751                 g_free(path);
2752                 g_warning(_("can't save message\n"));
2753                 return -1;
2754         }
2755
2756         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
2757                 g_warning(_("can't open mark file\n"));
2758         else {
2759                 MsgInfo newmsginfo;
2760
2761                 newmsginfo.msgnum = num;
2762                 newmsginfo.flags.perm_flags = 0;
2763                 newmsginfo.flags.tmp_flags = 0;
2764                 procmsg_write_flags(&newmsginfo, fp);
2765                 fclose(fp);
2766         }
2767         g_free(path);
2768
2769         return 0;
2770 }
2771
2772 static gint compose_remove_reedit_target(Compose *compose)
2773 {
2774         FolderItem *item;
2775         MsgInfo *msginfo = compose->targetinfo;
2776
2777         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
2778         if (!msginfo) return -1;
2779
2780         item = msginfo->folder;
2781         g_return_val_if_fail(item != NULL, -1);
2782
2783         folder_item_scan(item);
2784         if (procmsg_msg_exist(msginfo) &&
2785             (item->stype == F_DRAFT || item->stype == F_QUEUE)) {
2786                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
2787                         g_warning(_("can't remove the old message\n"));
2788                         return -1;
2789                 }
2790         }
2791
2792         return 0;
2793 }
2794
2795 static gint compose_queue(Compose *compose, const gchar *file)
2796 {
2797         FolderItem *queue;
2798         gchar *tmp, *queue_path;
2799         FILE *fp, *src_fp;
2800         GSList *cur;
2801         gchar buf[BUFFSIZE];
2802         gint num;
2803
2804         debug_print(_("queueing message...\n"));
2805         g_return_val_if_fail(compose->to_list != NULL, -1);
2806         g_return_val_if_fail(compose->account != NULL, -1);
2807
2808         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
2809                               G_DIR_SEPARATOR, (gint)compose);
2810         if ((fp = fopen(tmp, "w")) == NULL) {
2811                 FILE_OP_ERROR(tmp, "fopen");
2812                 g_free(tmp);
2813                 return -1;
2814         }
2815         if ((src_fp = fopen(file, "r")) == NULL) {
2816                 FILE_OP_ERROR(file, "fopen");
2817                 fclose(fp);
2818                 unlink(tmp);
2819                 g_free(tmp);
2820                 return -1;
2821         }
2822         if (change_file_mode_rw(fp, tmp) < 0) {
2823                 FILE_OP_ERROR(tmp, "chmod");
2824                 g_warning(_("can't change file mode\n"));
2825         }
2826
2827         /* queueing variables */
2828         fprintf(fp, "AF:\n");
2829         fprintf(fp, "NF:0\n");
2830         fprintf(fp, "PS:10\n");
2831         fprintf(fp, "SRH:1\n");
2832         fprintf(fp, "SFN:\n");
2833         fprintf(fp, "DSR:\n");
2834         if (compose->msgid)
2835                 fprintf(fp, "MID:<%s>\n", compose->msgid);
2836         else
2837                 fprintf(fp, "MID:\n");
2838         fprintf(fp, "CFG:\n");
2839         fprintf(fp, "PT:0\n");
2840         fprintf(fp, "S:%s\n", compose->account->address);
2841         fprintf(fp, "RQ:\n");
2842         if (compose->account->smtp_server)
2843                 fprintf(fp, "SSV:%s\n", compose->account->smtp_server);
2844         else
2845                 fprintf(fp, "SSV:\n");
2846         if (compose->account->nntp_server)
2847                 fprintf(fp, "NSV:%s\n", compose->account->nntp_server);
2848         else
2849                 fprintf(fp, "NSV:\n");
2850         fprintf(fp, "SSH:\n");
2851         fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
2852         for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
2853                 fprintf(fp, ",<%s>", (gchar *)cur->data);
2854         fprintf(fp, "\n");
2855         /* Sylpheed account ID */
2856         fprintf(fp, "AID:%d\n", compose->account->account_id);
2857         fprintf(fp, "\n");
2858
2859         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2860                 if (fputs(buf, fp) == EOF) {
2861                         FILE_OP_ERROR(tmp, "fputs");
2862                         fclose(fp);
2863                         fclose(src_fp);
2864                         unlink(tmp);
2865                         g_free(tmp);
2866                         return -1;
2867                 }
2868         }
2869
2870         fclose(src_fp);
2871         if (fclose(fp) == EOF) {
2872                 FILE_OP_ERROR(tmp, "fclose");
2873                 unlink(tmp);
2874                 g_free(tmp);
2875                 return -1;
2876         }
2877
2878         queue = folder_get_default_queue();
2879
2880         folder_item_scan(queue);
2881         queue_path = folder_item_get_path(queue);
2882         if (!is_dir_exist(queue_path))
2883                 make_dir_hier(queue_path);
2884         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
2885                 g_warning(_("can't queue the message\n"));
2886                 unlink(tmp);
2887                 g_free(tmp);
2888                 g_free(queue_path);
2889                 return -1;
2890         }
2891         g_free(tmp);
2892
2893         if (compose->mode == COMPOSE_REEDIT) {
2894                 compose_remove_reedit_target(compose);
2895                 if (compose->targetinfo &&
2896                     compose->targetinfo->folder != queue)
2897                         folderview_update_item
2898                                 (compose->targetinfo->folder, TRUE);
2899         }
2900
2901         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
2902                 g_warning(_("can't open mark file\n"));
2903         else {
2904                 MsgInfo newmsginfo;
2905
2906                 newmsginfo.msgnum = num;
2907                 newmsginfo.flags.perm_flags = 0;
2908                 newmsginfo.flags.tmp_flags = 0;
2909                 procmsg_write_flags(&newmsginfo, fp);
2910                 fclose(fp);
2911         }
2912         g_free(queue_path);
2913
2914         folder_item_scan(queue);
2915         folderview_update_item(queue, TRUE);
2916
2917         return 0;
2918 }
2919
2920 static void compose_write_attach(Compose *compose, FILE *fp)
2921 {
2922         AttachInfo *ainfo;
2923         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2924         gint row;
2925         FILE *attach_fp;
2926         gchar filename[BUFFSIZE];
2927         gint len;
2928
2929         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
2930              row++) {
2931                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
2932                         g_warning(_("Can't open file %s\n"), ainfo->file);
2933                         continue;
2934                 }
2935
2936                 fprintf(fp, "\n--%s\n", compose->boundary);
2937
2938                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
2939                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
2940                         fprintf(fp, "Content-Disposition: inline\n");
2941                 } else {
2942                         conv_encode_header(filename, sizeof(filename),
2943                                            ainfo->name, 12);
2944                         fprintf(fp, "Content-Type: %s;\n"
2945                                     " name=\"%s\"\n",
2946                                 ainfo->content_type, filename);
2947                         fprintf(fp, "Content-Disposition: attachment;\n"
2948                                     " filename=\"%s\"\n", filename);
2949                 }
2950
2951                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
2952                         procmime_get_encoding_str(ainfo->encoding));
2953
2954                 if (ainfo->encoding == ENC_7BIT) {
2955                         gchar buf[BUFFSIZE];
2956
2957                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
2958                                 strcrchomp(buf);
2959                                 fputs(buf, fp);
2960                         }
2961                 } else {
2962                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
2963
2964                         while ((len = fread(inbuf, sizeof(gchar),
2965                                             B64_LINE_SIZE, attach_fp))
2966                                == B64_LINE_SIZE) {
2967                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
2968                                 fputs(outbuf, fp);
2969                                 fputc('\n', fp);
2970                         }
2971                         if (len > 0 && feof(attach_fp)) {
2972                                 to64frombits(outbuf, inbuf, len);
2973                                 fputs(outbuf, fp);
2974                                 fputc('\n', fp);
2975                         }
2976                 }
2977
2978                 fclose(attach_fp);
2979         }
2980
2981         fprintf(fp, "\n--%s--\n", compose->boundary);
2982 }
2983
2984 #define IS_IN_CUSTOM_HEADER(header) \
2985         (compose->account->add_customhdr && \
2986          custom_header_find(compose->account->customhdr_list, header) != NULL)
2987
2988 static gint compose_write_headers_from_headerlist(Compose *compose, 
2989                                                   FILE *fp, 
2990                                                   gchar *header,
2991                                                   GSList *(*list_append_func) (GSList *list, const gchar *str),
2992                                                   GSList **dest_list)
2993 {
2994         gchar buf[BUFFSIZE];
2995         gchar *str, *header_w_colon, *trans_hdr;
2996         gboolean first_address;
2997         GSList *list;
2998         compose_headerentry *headerentry;
2999
3000         if (IS_IN_CUSTOM_HEADER(header)) {
3001                 return 0;
3002         }
3003
3004         debug_print(_("Writing %s-header\n"), header);
3005
3006         header_w_colon = g_strconcat(header, ":", NULL);
3007         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3008
3009         first_address = TRUE;
3010         for(list = compose->header_list; list; list = list->next) {
3011                 headerentry = ((compose_headerentry *)list->data);
3012                 if(!strcmp(trans_hdr, gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)))) {
3013                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3014                         Xstrdup_a(str, str, return -1);
3015                         g_strstrip(str);
3016                         if(str[0] != '\0') {
3017                                 if(list_append_func)
3018                                         *dest_list = list_append_func(*dest_list, str);
3019                                 compose_convert_header
3020                                         (buf, sizeof(buf), str,
3021                                         strlen(header) + 2);
3022                                 if(first_address) {
3023                                         fprintf(fp, "%s: ", header);
3024                                         first_address = FALSE;
3025                                 } else {
3026                                         fprintf(fp, ", ");
3027                                 }
3028                                 fprintf(fp, "%s", buf);
3029                         }
3030                 }
3031         }
3032         if(!first_address) {
3033                 fprintf(fp, "\n");
3034         }
3035
3036         g_free(header_w_colon);
3037
3038         return(0);
3039 }
3040
3041 static gint compose_write_headers(Compose *compose, FILE *fp,
3042                                   const gchar *charset, EncodingType encoding,
3043                                   gboolean is_draft)
3044 {
3045         gchar buf[BUFFSIZE];
3046         gchar *str;
3047         /* struct utsname utsbuf; */
3048
3049         g_return_val_if_fail(fp != NULL, -1);
3050         g_return_val_if_fail(charset != 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         /* Date */
3055         if (compose->account->add_date) {
3056                 get_rfc822_date(buf, sizeof(buf));
3057                 fprintf(fp, "Date: %s\n", buf);
3058         }
3059
3060         /* From */
3061         if (!IS_IN_CUSTOM_HEADER("From")) {
3062                 if (compose->account->name && *compose->account->name) {
3063                         compose_convert_header
3064                                 (buf, sizeof(buf), compose->account->name,
3065                                  strlen("From: "));
3066                         fprintf(fp, "From: %s <%s>\n",
3067                                 buf, compose->account->address);
3068                 } else
3069                         fprintf(fp, "From: %s\n", compose->account->address);
3070         }
3071         
3072         slist_free_strings(compose->to_list);
3073         g_slist_free(compose->to_list);
3074         compose->to_list = NULL;
3075
3076         /* To */
3077         compose_write_headers_from_headerlist(compose, fp, "To", address_list_append, &compose->to_list);
3078 #if 0 /* NEW COMPOSE GUI */
3079         if (compose->use_to) {
3080                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3081                 if (*str != '\0') {
3082                         Xstrdup_a(str, str, return -1);
3083                         g_strstrip(str);
3084                         if (*str != '\0') {
3085                                 compose->to_list = address_list_append
3086                                         (compose->to_list, str);
3087                                 if (!IS_IN_CUSTOM_HEADER("To")) {
3088                                         compose_convert_header
3089                                                 (buf, sizeof(buf), str,
3090                                                  strlen("To: "));
3091                                         fprintf(fp, "To: %s\n", buf);
3092                                 }
3093                         }
3094                 }
3095         }
3096 #endif
3097         slist_free_strings(compose->newsgroup_list);
3098         g_slist_free(compose->newsgroup_list);
3099         compose->newsgroup_list = NULL;
3100
3101         /* Newsgroups */
3102         compose_write_headers_from_headerlist(compose, fp, "Newsgroups", newsgroup_list_append, &compose->newsgroup_list);
3103 #if 0 /* NEW COMPOSE GUI */
3104         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3105         if (*str != '\0') {
3106                 Xstrdup_a(str, str, return -1);
3107                 g_strstrip(str);
3108                 remove_space(str);
3109                 if (*str != '\0') {
3110                         compose->newsgroup_list =
3111                                 newsgroup_list_append(compose->newsgroup_list,
3112                                                       str);
3113                         if (!IS_IN_CUSTOM_HEADER("Newsgroups")) {
3114                                 compose_convert_header(buf, sizeof(buf), str,
3115                                                        strlen("Newsgroups: "));
3116                                 fprintf(fp, "Newsgroups: %s\n", buf);
3117                         }
3118                 }
3119         }
3120 #endif
3121         /* Cc */
3122         compose_write_headers_from_headerlist(compose, fp, "Cc", address_list_append, &compose->to_list);
3123 #if 0 /* NEW COMPOSE GUI */
3124         if (compose->use_cc) {
3125                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
3126                 if (*str != '\0') {
3127                         Xstrdup_a(str, str, return -1);
3128                         g_strstrip(str);
3129                         if (*str != '\0') {
3130                                 compose->to_list = address_list_append
3131                                         (compose->to_list, str);
3132                                 if (!IS_IN_CUSTOM_HEADER("Cc")) {
3133                                         compose_convert_header
3134                                                 (buf, sizeof(buf), str,
3135                                                  strlen("Cc: "));
3136                                         fprintf(fp, "Cc: %s\n", buf);
3137                                 }
3138                         }
3139                 }
3140         }
3141 #endif
3142         /* Bcc */
3143         compose_write_headers_from_headerlist(compose, fp, "Bcc", address_list_append, &compose->to_list);
3144 #if 0 /* NEW COMPOSE GUI */
3145         if (compose->use_bcc) {
3146                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
3147                 if (*str != '\0') {
3148                         Xstrdup_a(str, str, return -1);
3149                         g_strstrip(str);
3150                         if (*str != '\0') {
3151                                 compose->to_list = address_list_append
3152                                         (compose->to_list, str);
3153                                 compose_convert_header(buf, sizeof(buf), str,
3154                                                        strlen("Bcc: "));
3155                                 fprintf(fp, "Bcc: %s\n", buf);
3156                         }
3157                 }
3158         }
3159 #endif
3160         if (!is_draft && !compose->to_list && !compose->newsgroup_list)
3161                 return -1;
3162
3163         /* Subject */
3164         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3165         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
3166                 Xstrdup_a(str, str, return -1);
3167                 g_strstrip(str);
3168                 if (*str != '\0') {
3169                         compose_convert_header(buf, sizeof(buf), str,
3170                                                strlen("Subject: "));
3171                         fprintf(fp, "Subject: %s\n", buf);
3172                 }
3173         }
3174
3175         /* Message-ID */
3176         if (compose->account->gen_msgid) {
3177                 compose_generate_msgid(compose, buf, sizeof(buf));
3178                 fprintf(fp, "Message-Id: <%s>\n", buf);
3179                 compose->msgid = g_strdup(buf);
3180         }
3181
3182         /* In-Reply-To */
3183         if (compose->inreplyto && compose->to_list)
3184                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
3185
3186         /* References */
3187         if (compose->references)
3188                 fprintf(fp, "References: %s\n", compose->references);
3189
3190         /* Followup-To */
3191         compose_write_headers_from_headerlist(compose, fp, "Followup-To", NULL, NULL);
3192 #if 0 /* NEW COMPOSE GUI */
3193         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
3194                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
3195                 if (*str != '\0') {
3196                         Xstrdup_a(str, str, return -1);
3197                         g_strstrip(str);
3198                         remove_space(str);
3199                         if (*str != '\0') {
3200                                 compose_convert_header(buf, sizeof(buf), str,
3201                                                        strlen("Followup-To: "));
3202                                 fprintf(fp, "Followup-To: %s\n", buf);
3203                         }
3204                 }
3205         }
3206 #endif
3207         /* Reply-To */
3208         compose_write_headers_from_headerlist(compose, fp, "Reply-To", NULL, NULL);
3209 #if 0 /* NEW COMPOSE GUI */
3210         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
3211                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
3212                 if (*str != '\0') {
3213                         Xstrdup_a(str, str, return -1);
3214                         g_strstrip(str);
3215                         if (*str != '\0') {
3216                                 compose_convert_header(buf, sizeof(buf), str,
3217                                                        strlen("Reply-To: "));
3218                                 fprintf(fp, "Reply-To: %s\n", buf);
3219                         }
3220                 }
3221         }
3222 #endif
3223         /* Organization */
3224         if (compose->account->organization &&
3225             !IS_IN_CUSTOM_HEADER("Organization")) {
3226                 compose_convert_header(buf, sizeof(buf),
3227                                        compose->account->organization,
3228                                        strlen("Organization: "));
3229                 fprintf(fp, "Organization: %s\n", buf);
3230         }
3231
3232         /* Program version and system info */
3233         /* uname(&utsbuf); */
3234         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
3235                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
3236                         prog_version,
3237                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3238                         HOST_ALIAS);
3239                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3240         }
3241         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
3242                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
3243                         prog_version,
3244                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3245                         HOST_ALIAS);
3246                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3247         }
3248
3249         /* custom headers */
3250         if (compose->account->add_customhdr) {
3251                 GSList *cur;
3252
3253                 for (cur = compose->account->customhdr_list; cur != NULL;
3254                      cur = cur->next) {
3255                         CustomHeader *chdr = (CustomHeader *)cur->data;
3256
3257                         if (strcasecmp(chdr->name, "Date")                      != 0 &&
3258                             strcasecmp(chdr->name, "From")                      != 0 &&
3259                             strcasecmp(chdr->name, "To")                        != 0 &&
3260                             strcasecmp(chdr->name, "Sender")                    != 0 &&
3261                             strcasecmp(chdr->name, "Message-Id")                != 0 &&
3262                             strcasecmp(chdr->name, "In-Reply-To")               != 0 &&
3263                             strcasecmp(chdr->name, "References")                != 0 &&
3264                             strcasecmp(chdr->name, "Mime-Version")              != 0 &&
3265                             strcasecmp(chdr->name, "Content-Type")              != 0 &&
3266                             strcasecmp(chdr->name, "Content-Transfer-Encoding") != 0)
3267                                 compose_convert_header
3268                                         (buf, sizeof(buf),
3269                                          chdr->value ? chdr->value : "",
3270                                          strlen(chdr->name) + 2);
3271                         fprintf(fp, "%s: %s\n", chdr->name, buf);
3272                 }
3273         }
3274
3275         /* MIME */
3276         fprintf(fp, "Mime-Version: 1.0\n");
3277         if (compose_use_attach(compose)) {
3278                 get_rfc822_date(buf, sizeof(buf));
3279                 subst_char(buf, ' ', '_');
3280                 subst_char(buf, ',', '_');
3281                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
3282                                                     buf, (guint)compose);
3283                 fprintf(fp,
3284                         "Content-Type: multipart/mixed;\n"
3285                         " boundary=\"%s\"\n", compose->boundary);
3286         } else {
3287                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
3288                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3289                         procmime_get_encoding_str(encoding));
3290         }
3291
3292         /* Request Return Receipt */
3293         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
3294                 if (compose->return_receipt) {
3295                         if (compose->account->name
3296                             && *compose->account->name) {
3297                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
3298                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
3299                         } else
3300                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
3301                 }
3302         }
3303
3304         /* separator between header and body */
3305         fputs("\n", fp);
3306
3307         return 0;
3308 }
3309
3310 #undef IS_IN_CUSTOM_HEADER
3311
3312 static void compose_convert_header(gchar *dest, gint len, gchar *src,
3313                                    gint header_len)
3314 {
3315         g_return_if_fail(src != NULL);
3316         g_return_if_fail(dest != NULL);
3317
3318         if (len < 1) return;
3319
3320         remove_return(src);
3321
3322         if (is_ascii_str(src)) {
3323                 strncpy2(dest, src, len);
3324                 dest[len - 1] = '\0';
3325                 return;
3326         } else
3327                 conv_encode_header(dest, len, src, header_len);
3328 }
3329
3330 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
3331 {
3332         struct tm *lt;
3333         time_t t;
3334         gchar *addr;
3335
3336         t = time(NULL);
3337         lt = localtime(&t);
3338
3339         if (compose->account && compose->account->address &&
3340             *compose->account->address) {
3341                 if (strchr(compose->account->address, '@'))
3342                         addr = g_strdup(compose->account->address);
3343                 else
3344                         addr = g_strconcat(compose->account->address, "@",
3345                                            get_domain_name(), NULL);
3346         } else
3347                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3348                                    NULL);
3349
3350         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3351                    lt->tm_year + 1900, lt->tm_mon + 1,
3352                    lt->tm_mday, lt->tm_hour,
3353                    lt->tm_min, lt->tm_sec,
3354                    (guint)random(), addr);
3355
3356         debug_print(_("generated Message-ID: %s\n"), buf);
3357
3358         g_free(addr);
3359 }
3360
3361
3362 static void compose_add_entry_field(GtkWidget *table, GtkWidget **hbox,
3363                                     GtkWidget **entry, gint *count,
3364                                     const gchar *label_str,
3365                                     gboolean is_addr_entry)
3366 {
3367         GtkWidget *label;
3368
3369         if (GTK_TABLE(table)->nrows < (*count) + 1)
3370                 gtk_table_resize(GTK_TABLE(table), (*count) + 1, 2);
3371
3372         *hbox = gtk_hbox_new(FALSE, 0);
3373         label = gtk_label_new
3374                 (prefs_common.trans_hdr ? gettext(label_str) : label_str);
3375         gtk_box_pack_end(GTK_BOX(*hbox), label, FALSE, FALSE, 0);
3376         gtk_table_attach(GTK_TABLE(table), *hbox, 0, 1, *count, (*count) + 1,
3377                          GTK_FILL, 0, 2, 0);
3378         *entry = gtk_entry_new();
3379         gtk_table_attach
3380                 (GTK_TABLE(table), *entry, 1, 2, *count, (*count) + 1, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0);
3381 #if 0 /* NEW COMPOSE GUI */
3382         if (GTK_TABLE(table)->nrows > (*count) + 1)
3383                 gtk_table_set_row_spacing(GTK_TABLE(table), *count, 4);
3384 #endif
3385
3386         if (is_addr_entry)
3387                 address_completion_register_entry(GTK_ENTRY(*entry));
3388
3389         (*count)++;
3390 }
3391
3392 static void compose_create_header_entry(Compose *compose) {
3393         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3394
3395         GtkWidget *combo;
3396         GtkWidget *entry;
3397         GList *combo_list = NULL;
3398         gchar **string, *header;
3399         compose_headerentry *headerentry = g_new0(compose_headerentry, 1);
3400
3401         /* Combo box */
3402         combo = gtk_combo_new();
3403         string = headers; 
3404         while(*string != NULL) {
3405             combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
3406             string++;
3407         }
3408         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
3409         g_list_free(combo_list);
3410         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), FALSE);
3411         gtk_widget_show(combo);
3412         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
3413         if(compose->header_last) {      
3414                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
3415         } else {
3416                 switch(compose->account->protocol) {
3417                         case A_NNTP:
3418                                 header = _("Newsgroups:");
3419                                 break;
3420                         default:
3421                                 header = _("To:");
3422                                 break;
3423                 }                                                                   
3424         }
3425         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
3426
3427         /* Entry field */
3428         entry = gtk_entry_new(); 
3429         gtk_widget_show(entry);
3430         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);
3431
3432         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
3433         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
3434
3435         address_completion_register_entry(GTK_ENTRY(entry));
3436
3437         headerentry->compose = compose;
3438         headerentry->combo = combo;
3439         headerentry->entry = entry;
3440         headerentry->headernum = compose->header_nextrow;
3441
3442         compose->header_nextrow++;
3443         compose->header_last = headerentry;
3444 }
3445
3446 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) {
3447         compose_headerentry *last_header;
3448         
3449         last_header = compose->header_last;
3450         
3451         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
3452         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
3453 }
3454
3455 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
3456 {
3457         Compose   *compose;
3458         GtkWidget *window;
3459         GtkWidget *vbox;
3460         GtkWidget *menubar;
3461         GtkWidget *handlebox;
3462
3463         GtkWidget *notebook;
3464
3465         GtkWidget *vbox2;
3466
3467         GtkWidget *table_vbox;
3468         GtkWidget *label;
3469         GtkWidget *from_optmenu_hbox;
3470 #if 0 /* NEW COMPOSE GUI */
3471         GtkWidget *to_entry;
3472         GtkWidget *to_hbox;
3473         GtkWidget *newsgroups_entry;
3474         GtkWidget *newsgroups_hbox;
3475 #endif
3476         GtkWidget *header_scrolledwin;
3477         GtkWidget *header_table;
3478         GtkWidget *subject_entry;
3479 #if 0 /* NEW COMPOSE GUI */
3480         GtkWidget *cc_entry;
3481         GtkWidget *cc_hbox;
3482         GtkWidget *bcc_entry;
3483         GtkWidget *bcc_hbox;
3484         GtkWidget *reply_entry;
3485         GtkWidget *reply_hbox;
3486         GtkWidget *followup_entry;
3487         GtkWidget *followup_hbox;
3488 #endif
3489         GtkWidget *paned;
3490
3491         GtkWidget *attach_scrwin;
3492         GtkWidget *attach_clist;
3493
3494         GtkWidget *edit_vbox;
3495         GtkWidget *ruler_hbox;
3496         GtkWidget *ruler;
3497         GtkWidget *scrolledwin;
3498         GtkWidget *text;
3499
3500         GtkWidget *table;
3501         GtkWidget *hbox;
3502
3503         gchar *titles[] = {_("MIME type"), _("Size"), _("Name")};
3504         guint n_menu_entries;
3505         GtkStyle  *style, *new_style;
3506         GdkColormap *cmap;
3507         GdkColor color[1];
3508         gboolean success[1];
3509         GdkFont   *font;
3510         GtkWidget *popupmenu;
3511         GtkWidget *menuitem;
3512         GtkItemFactory *popupfactory;
3513         GtkItemFactory *ifactory;
3514         GtkWidget *tmpl_menu;
3515         gint n_entries;
3516         gint count = 0;
3517         gint i;
3518
3519 #if USE_PSPELL
3520         GtkPspell * gtkpspell = NULL;
3521 #endif
3522
3523         g_return_val_if_fail(account != NULL, NULL);
3524
3525         debug_print(_("Creating compose window...\n"));
3526         compose = g_new0(Compose, 1);
3527
3528         compose->account = account;
3529         compose->orig_account = account;
3530
3531         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3532         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
3533         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
3534         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
3535                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
3536         gtk_signal_connect(GTK_OBJECT(window), "destroy",
3537                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
3538         gtk_signal_connect(GTK_OBJECT(window), "focus_in_event",
3539                            GTK_SIGNAL_FUNC(manage_window_focus_in), NULL);
3540         gtk_signal_connect(GTK_OBJECT(window), "focus_out_event",
3541                            GTK_SIGNAL_FUNC(manage_window_focus_out), NULL);
3542         gtk_widget_realize(window);
3543
3544         gtkut_widget_set_composer_icon(window);
3545
3546         vbox = gtk_vbox_new(FALSE, 0);
3547         gtk_container_add(GTK_CONTAINER(window), vbox);
3548
3549         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
3550         menubar = menubar_create(window, compose_entries,
3551                                  n_menu_entries, "<Compose>", compose);
3552         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
3553
3554         handlebox = gtk_handle_box_new();
3555         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
3556
3557         compose_toolbar_create(compose, handlebox);
3558
3559         vbox2 = gtk_vbox_new(FALSE, 2);
3560         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
3561         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
3562
3563         table_vbox = gtk_vbox_new(FALSE, 0);
3564         gtk_box_pack_start(GTK_BOX(vbox2), table_vbox, FALSE, TRUE, 0);
3565         gtk_container_set_border_width(GTK_CONTAINER(table_vbox),
3566                                        BORDER_WIDTH * 2);
3567
3568         /* Notebook */
3569         notebook = gtk_notebook_new();
3570         gtk_widget_set_usize(notebook, -1, 180);
3571         gtk_widget_show(notebook);
3572
3573         /* header labels and entries */
3574         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
3575         gtk_widget_show(header_scrolledwin);
3576         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
3577         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), header_scrolledwin, gtk_label_new(_("Header")));
3578
3579         header_table = gtk_table_new(2, 2, FALSE);
3580         gtk_widget_show(header_table);
3581         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
3582         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
3583         count = 0;
3584
3585         /* option menu for selecting accounts */
3586         hbox = gtk_hbox_new(FALSE, 0);
3587         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
3588         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
3589         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
3590                          GTK_FILL, 0, 2, 0);
3591         from_optmenu_hbox = compose_account_option_menu_create(compose);
3592         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
3593                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
3594 #if 0 /* NEW COMPOSE GUI */
3595         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
3596 #endif
3597         count++;
3598
3599         /* Subject */
3600         compose_add_entry_field(header_table, &hbox, &subject_entry, &count,
3601                                 "Subject:", FALSE);
3602
3603         compose->header_table = header_table;
3604         compose->header_list = NULL;
3605         compose->header_nextrow = count;
3606
3607         compose_create_header_entry(compose);
3608
3609 #if 0 /* NEW COMPOSE GUI */
3610         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
3611                                 "To:", TRUE); 
3612         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
3613         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
3614                                 &count, "Newsgroups:", FALSE);
3615         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
3616
3617         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
3618
3619         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
3620                                 "Cc:", TRUE);
3621         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
3622         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
3623                                 "Bcc:", TRUE);
3624         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
3625         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
3626                                 "Reply-To:", TRUE);
3627         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
3628         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
3629                                 "Followup-To:", FALSE);
3630         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
3631
3632         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
3633
3634         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
3635                            GTK_SIGNAL_FUNC(to_activated), compose);
3636         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
3637                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
3638         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
3639                            GTK_SIGNAL_FUNC(subject_activated), compose);
3640         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
3641                            GTK_SIGNAL_FUNC(cc_activated), compose);
3642         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
3643                            GTK_SIGNAL_FUNC(bcc_activated), compose);
3644         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
3645                            GTK_SIGNAL_FUNC(replyto_activated), compose);
3646         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
3647                            GTK_SIGNAL_FUNC(followupto_activated), compose);
3648
3649         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
3650                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3651         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
3652                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3653         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
3654                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3655         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
3656                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3657         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
3658                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3659         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
3660                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3661         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
3662                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3663 #endif
3664
3665         /* attachment list */
3666         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
3667         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), attach_scrwin, gtk_label_new(_("Attachments")));
3668         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
3669                                        GTK_POLICY_AUTOMATIC,
3670                                        GTK_POLICY_ALWAYS);
3671         gtk_widget_set_usize(attach_scrwin, -1, 80);
3672
3673         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
3674         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
3675                                            GTK_JUSTIFY_RIGHT);
3676         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
3677         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
3678         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
3679                                      GTK_SELECTION_EXTENDED);
3680         for (i = 0; i < N_ATTACH_COLS; i++)
3681                 GTK_WIDGET_UNSET_FLAGS
3682                         (GTK_CLIST(attach_clist)->column[i].button,
3683                          GTK_CAN_FOCUS);
3684         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
3685
3686         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
3687                            GTK_SIGNAL_FUNC(attach_selected), compose);
3688         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
3689                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
3690         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
3691                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
3692
3693         /* drag and drop */
3694         gtk_drag_dest_set(attach_clist,
3695                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
3696                           GDK_ACTION_COPY);
3697         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
3698                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
3699                            compose);
3700
3701
3702         edit_vbox = gtk_vbox_new(FALSE, 0);
3703 #if 0 /* NEW COMPOSE GUI */
3704         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
3705 #endif
3706
3707         /* ruler */
3708         ruler_hbox = gtk_hbox_new(FALSE, 0);
3709         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
3710
3711         ruler = gtk_shruler_new();
3712         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
3713         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
3714                            BORDER_WIDTH + 1);
3715         gtk_widget_set_usize(ruler_hbox, 1, -1);
3716
3717         /* text widget */
3718         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
3719         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
3720                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
3721         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
3722         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
3723
3724         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
3725                             (GTK_SCROLLED_WINDOW(scrolledwin)),
3726                             gtk_scrolled_window_get_vadjustment
3727                             (GTK_SCROLLED_WINDOW(scrolledwin)));
3728         GTK_STEXT(text)->default_tab_width = 8;
3729         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
3730
3731         if (prefs_common.block_cursor) {
3732                 GTK_STEXT(text)->cursor_type = STEXT_CURSOR_BLOCK;
3733         }
3734         
3735         if (prefs_common.smart_wrapping) {      
3736                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
3737                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
3738         }               
3739
3740         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
3741
3742         gtk_signal_connect(GTK_OBJECT(text), "changed",
3743                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
3744         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
3745                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3746         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
3747                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
3748                                  compose);
3749 #if 0
3750         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
3751                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
3752                                  compose);
3753 #endif
3754         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
3755                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
3756                                  ruler);
3757
3758         /* drag and drop */
3759         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
3760                           GDK_ACTION_COPY);
3761         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
3762                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
3763                            compose);
3764 #if USE_PSPELL
3765         if (prefs_common.enable_pspell) {
3766                 gtkpspell = gtkpspell_new_with_config(gtkpspellconfig,
3767                                                       prefs_common.pspell_path,
3768                                                       prefs_common.dictionary,
3769                                                       PSPELL_FASTMODE,
3770                                                       conv_get_current_charset_str());
3771                 if (gtkpspell == NULL)
3772                         prefs_common.enable_pspell = FALSE;
3773                 else
3774                         gtkpspell_attach(gtkpspell, GTK_STEXT(text));
3775         }
3776 #endif
3777         gtk_widget_show_all(vbox);
3778
3779         /* pane between attach clist and text */
3780         paned = gtk_vpaned_new();
3781         gtk_container_add(GTK_CONTAINER(vbox2), paned);
3782         gtk_paned_add1(GTK_PANED(paned), notebook);
3783         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
3784         gtk_widget_show_all(paned);
3785
3786         style = gtk_widget_get_style(text);
3787
3788         /* workaround for the slow down of GtkText when using Pixmap theme */
3789         if (style->engine) {
3790                 GtkThemeEngine *engine;
3791
3792                 engine = style->engine;
3793                 style->engine = NULL;
3794                 new_style = gtk_style_copy(style);
3795                 style->engine = engine;
3796         } else
3797                 new_style = gtk_style_copy(style);
3798
3799         if (prefs_common.textfont) {
3800                 CharSet charset;
3801
3802                 charset = conv_get_current_charset();
3803                 if (MB_CUR_MAX == 1) {
3804                         gchar *fontstr, *p;
3805
3806                         Xstrdup_a(fontstr, prefs_common.textfont, );
3807                         if (fontstr && (p = strchr(fontstr, ',')) != NULL)
3808                                 *p = '\0';
3809                         font = gdk_font_load(fontstr);
3810                 } else
3811                         font = gdk_fontset_load(prefs_common.textfont);
3812                 if (font) {
3813                         gdk_font_unref(new_style->font);
3814                         new_style->font = font;
3815                 }
3816         }
3817
3818         gtk_widget_set_style(text, new_style);
3819
3820         color[0] = quote_color;
3821         cmap = gdk_window_get_colormap(window->window);
3822         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
3823         if (success[0] == FALSE) {
3824                 g_warning("Compose: color allocation failed.\n");
3825                 style = gtk_widget_get_style(text);
3826                 quote_color = style->black;
3827         }
3828
3829         n_entries = sizeof(compose_popup_entries) /
3830                 sizeof(compose_popup_entries[0]);
3831         popupmenu = menu_create_items(compose_popup_entries, n_entries,
3832                                       "<Compose>", &popupfactory,
3833                                       compose);
3834
3835         ifactory = gtk_item_factory_from_widget(menubar);
3836         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
3837         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
3838
3839         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tool/Template");
3840 #if 0 /* NEW COMPOSE GUI */
3841         if (account->protocol == A_NNTP) {
3842                 gtk_widget_hide(to_hbox);
3843                 gtk_widget_hide(to_entry);
3844                 gtk_widget_hide(cc_hbox);
3845                 gtk_widget_hide(cc_entry);
3846                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
3847                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
3848         } else {
3849                 gtk_widget_hide(newsgroups_hbox);
3850                 gtk_widget_hide(newsgroups_entry);
3851                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
3852
3853                 menu_set_sensitive(ifactory, "/Message/Followup to", FALSE);
3854         }
3855 #endif
3856
3857         switch (prefs_common.toolbar_style) {
3858         case TOOLBAR_NONE:
3859                 gtk_widget_hide(handlebox);
3860                 break;
3861         case TOOLBAR_ICON:
3862                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
3863                                       GTK_TOOLBAR_ICONS);
3864                 break;
3865         case TOOLBAR_TEXT:
3866                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
3867                                       GTK_TOOLBAR_TEXT);
3868                 break;
3869         case TOOLBAR_BOTH:
3870                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
3871                                       GTK_TOOLBAR_BOTH);
3872                 break;
3873         }
3874
3875         gtk_widget_show(window);
3876
3877         address_completion_start(window);
3878
3879         compose->window        = window;
3880         compose->vbox          = vbox;
3881         compose->menubar       = menubar;
3882         compose->handlebox     = handlebox;
3883
3884         compose->vbox2         = vbox2;
3885
3886         compose->table_vbox       = table_vbox;
3887         compose->table            = table;
3888 #if 0 /* NEW COMPOSE GUI */
3889         compose->to_hbox          = to_hbox;
3890         compose->to_entry         = to_entry;
3891         compose->newsgroups_hbox  = newsgroups_hbox;
3892         compose->newsgroups_entry = newsgroups_entry;
3893 #endif
3894         compose->subject_entry    = subject_entry;
3895 #if 0 /* NEW COMPOSE GUI */
3896         compose->cc_hbox          = cc_hbox;
3897         compose->cc_entry         = cc_entry;
3898         compose->bcc_hbox         = bcc_hbox;
3899         compose->bcc_entry        = bcc_entry;
3900         compose->reply_hbox       = reply_hbox;
3901         compose->reply_entry      = reply_entry;
3902         compose->followup_hbox    = followup_hbox;
3903         compose->followup_entry   = followup_entry;
3904 #endif
3905         compose->paned = paned;
3906
3907         compose->attach_scrwin = attach_scrwin;
3908         compose->attach_clist  = attach_clist;
3909
3910         compose->edit_vbox     = edit_vbox;
3911         compose->ruler_hbox    = ruler_hbox;
3912         compose->ruler         = ruler;
3913         compose->scrolledwin   = scrolledwin;
3914         compose->text          = text;
3915
3916         compose->focused_editable = NULL;
3917
3918         compose->popupmenu    = popupmenu;
3919         compose->popupfactory = popupfactory;
3920
3921         compose->tmpl_menu = tmpl_menu;
3922
3923         compose->mode = mode;
3924
3925         compose->targetinfo = NULL;
3926         compose->replyinfo  = NULL;
3927
3928         compose->replyto     = NULL;
3929         compose->mailinglist = NULL;
3930         compose->cc          = NULL;
3931         compose->bcc         = NULL;
3932         compose->followup_to = NULL;
3933         compose->inreplyto   = NULL;
3934         compose->references  = NULL;
3935         compose->msgid       = NULL;
3936         compose->boundary    = NULL;
3937
3938 #if USE_GPGME
3939         compose->use_signing    = FALSE;
3940         compose->use_encryption = FALSE;
3941 #endif /* USE_GPGME */
3942
3943         compose->modified = FALSE;
3944
3945         compose->return_receipt = FALSE;
3946
3947         compose->to_list        = NULL;
3948         compose->newsgroup_list = NULL;
3949
3950         compose->exteditor_file    = NULL;
3951         compose->exteditor_pid     = -1;
3952         compose->exteditor_readdes = -1;
3953         compose->exteditor_tag     = -1;
3954
3955         compose_set_title(compose);
3956
3957 #if 0 /* NEW COMPOSE GUI */
3958         compose->use_bcc        = FALSE;
3959         compose->use_replyto    = FALSE;
3960         compose->use_followupto = FALSE;
3961 #endif
3962
3963 #if USE_PSPELL
3964         compose->gtkpspell      = gtkpspell;
3965 #endif
3966
3967 #if 0 /* NEW COMPOSE GUI */
3968         if (account->protocol != A_NNTP) {
3969                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
3970                 gtk_check_menu_item_set_active
3971                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3972                 gtk_widget_set_sensitive(menuitem, FALSE);
3973                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
3974                 gtk_check_menu_item_set_active
3975                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3976                 gtk_widget_set_sensitive(menuitem, FALSE);
3977         }
3978 #endif
3979         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT) {
3980                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
3981 #if 0 /* NEW COMPOSE GUI */
3982                 compose->use_cc = TRUE;
3983                 gtk_entry_set_text(GTK_ENTRY(cc_entry), account->auto_cc);
3984                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
3985                 gtk_check_menu_item_set_active
3986                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3987 #endif
3988         }
3989         if (account->set_autobcc) {
3990                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
3991 #if 0 /* NEW COMPOSE GUI */
3992                 compose->use_bcc = TRUE;
3993                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
3994                 gtk_check_menu_item_set_active
3995                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3996                 if (account->auto_bcc && mode != COMPOSE_REEDIT)
3997                         gtk_entry_set_text(GTK_ENTRY(bcc_entry),
3998                                            account->auto_bcc);
3999 #endif
4000         }
4001         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT) {
4002                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
4003 #if 0 /* NEW COMPOSE GUI */
4004                 compose->use_replyto = TRUE;
4005                 menuitem = gtk_item_factory_get_item(ifactory,
4006                                                      "/Message/Reply to");
4007                 gtk_check_menu_item_set_active
4008                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4009                 gtk_entry_set_text(GTK_ENTRY(reply_entry),
4010                                    account->auto_replyto);
4011 #endif
4012         }
4013         if (account->protocol != A_NNTP) {
4014                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), _("To:"));
4015         } else {
4016                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), _("Newsgroups:"));
4017         }
4018
4019         menuitem = gtk_item_factory_get_item(ifactory, "/Tool/Show ruler");
4020         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4021                                        prefs_common.show_ruler);
4022
4023 #if USE_GPGME
4024         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
4025         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4026                                        prefs_common.default_sign);
4027         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
4028         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4029                                        prefs_common.default_encrypt);
4030 #endif /* USE_GPGME */
4031
4032         addressbook_set_target_compose(compose);
4033         compose_set_template_menu(compose);
4034
4035         compose_list = g_list_append(compose_list, compose);
4036
4037 #if 0 /* NEW COMPOSE GUI */
4038         compose->use_to         = FALSE;
4039         compose->use_cc         = FALSE;
4040         compose->use_attach     = TRUE;
4041 #endif
4042
4043 #if 0 /* NEW COMPOSE GUI */
4044         if (!compose->use_bcc) {
4045                 gtk_widget_hide(bcc_hbox);
4046                 gtk_widget_hide(bcc_entry);
4047                 gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4048         }
4049         if (!compose->use_replyto) {
4050                 gtk_widget_hide(reply_hbox);
4051                 gtk_widget_hide(reply_entry);
4052                 gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4053         }
4054         if (!compose->use_followupto) {
4055                 gtk_widget_hide(followup_hbox);
4056                 gtk_widget_hide(followup_entry);
4057                 gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4058         }
4059 #endif
4060         if (!prefs_common.show_ruler)
4061                 gtk_widget_hide(ruler_hbox);
4062
4063         select_account(compose, account);
4064
4065         return compose;
4066 }
4067
4068 #include "pixmaps/stock_mail_send.xpm"
4069 #include "pixmaps/stock_mail_send_queue.xpm"
4070 #include "pixmaps/stock_mail.xpm"
4071 #include "pixmaps/stock_paste.xpm"
4072 #include "pixmaps/stock_mail_attach.xpm"
4073 #include "pixmaps/stock_mail_compose.xpm"
4074 #include "pixmaps/linewrap.xpm"
4075 #include "pixmaps/tb_address_book.xpm"
4076
4077 #define CREATE_TOOLBAR_ICON(xpm_d) \
4078 { \
4079         icon = gdk_pixmap_create_from_xpm_d(container->window, &mask, \
4080                                             &container->style->white, \
4081                                             xpm_d); \
4082         icon_wid = gtk_pixmap_new(icon, mask); \
4083 }
4084
4085 static void compose_toolbar_create(Compose *compose, GtkWidget *container)
4086 {
4087         GtkWidget *toolbar;
4088         GdkPixmap *icon;
4089         GdkBitmap *mask;
4090         GtkWidget *icon_wid;
4091         GtkWidget *send_btn;
4092         GtkWidget *sendl_btn;
4093         GtkWidget *draft_btn;
4094         GtkWidget *insert_btn;
4095         GtkWidget *attach_btn;
4096         GtkWidget *sig_btn;
4097         GtkWidget *exteditor_btn;
4098         GtkWidget *linewrap_btn;
4099         GtkWidget *addrbook_btn;
4100
4101         toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
4102                                   GTK_TOOLBAR_BOTH);
4103         gtk_container_add(GTK_CONTAINER(container), toolbar);
4104         gtk_container_set_border_width(GTK_CONTAINER(container), 2);
4105         gtk_toolbar_set_button_relief(GTK_TOOLBAR(toolbar), GTK_RELIEF_NONE);
4106         gtk_toolbar_set_space_style(GTK_TOOLBAR(toolbar),
4107                                     GTK_TOOLBAR_SPACE_LINE);
4108
4109         CREATE_TOOLBAR_ICON(stock_mail_send_xpm);
4110         send_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4111                                            _("Send"),
4112                                            _("Send message"),
4113                                            "Send",
4114                                            icon_wid, toolbar_send_cb, compose);
4115
4116         CREATE_TOOLBAR_ICON(stock_mail_send_queue_xpm);
4117         /* CREATE_TOOLBAR_ICON(tb_mail_queue_send_xpm); */
4118         sendl_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4119                                            _("Send later"),
4120                                            _("Put into queue folder and send later"),
4121                                            "Send later",
4122                                            icon_wid, toolbar_send_later_cb,
4123                                            compose);
4124
4125         CREATE_TOOLBAR_ICON(stock_mail_xpm);
4126         draft_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4127                                             _("Draft"),
4128                                             _("Save to draft folder"),
4129                                             "Draft",
4130                                             icon_wid, toolbar_draft_cb,
4131                                             compose);
4132
4133         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4134
4135         CREATE_TOOLBAR_ICON(stock_paste_xpm);
4136         insert_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4137                                              _("Insert"),
4138                                              _("Insert file"),
4139                                              "Insert",
4140                                              icon_wid, toolbar_insert_cb,
4141                                              compose);
4142
4143         CREATE_TOOLBAR_ICON(stock_mail_attach_xpm);
4144         attach_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4145                                              _("Attach"),
4146                                              _("Attach file"),
4147                                              "Attach",
4148                                              icon_wid, toolbar_attach_cb,
4149                                              compose);
4150
4151         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4152
4153         CREATE_TOOLBAR_ICON(stock_mail_xpm);
4154         sig_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4155                                           _("Signature"),
4156                                           _("Insert signature"),
4157                                           "Signature",
4158                                           icon_wid, toolbar_sig_cb, compose);
4159
4160         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4161
4162         CREATE_TOOLBAR_ICON(stock_mail_compose_xpm);
4163         exteditor_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4164                                                 _("Editor"),
4165                                                 _("Edit with external editor"),
4166                                                 "Editor",
4167                                                 icon_wid,
4168                                                 toolbar_ext_editor_cb,
4169                                                 compose);
4170
4171         CREATE_TOOLBAR_ICON(linewrap_xpm);
4172         linewrap_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4173                                                _("Linewrap"),
4174                                                _("Wrap current paragraph"),
4175                                                "Linewrap",
4176                                                icon_wid,
4177                                                toolbar_linewrap_cb,
4178                                                compose);
4179
4180         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4181
4182         CREATE_TOOLBAR_ICON(tb_address_book_xpm);
4183         addrbook_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4184                                                _("Address"),
4185                                                _("Address book"),
4186                                                "Address",
4187                                                icon_wid, toolbar_address_cb,
4188                                                compose);
4189
4190         compose->toolbar       = toolbar;
4191         compose->send_btn      = send_btn;
4192         compose->sendl_btn     = sendl_btn;
4193         compose->draft_btn     = draft_btn;
4194         compose->insert_btn    = insert_btn;
4195         compose->attach_btn    = attach_btn;
4196         compose->sig_btn       = sig_btn;
4197         compose->exteditor_btn = exteditor_btn;
4198         compose->linewrap_btn  = linewrap_btn;
4199         compose->addrbook_btn  = addrbook_btn;
4200
4201         gtk_widget_show_all(toolbar);
4202 }
4203
4204 #undef CREATE_TOOLBAR_ICON
4205
4206 static GtkWidget *compose_account_option_menu_create(Compose *compose)
4207 {
4208         GList *accounts;
4209         GtkWidget *hbox;
4210         GtkWidget *optmenu;
4211         GtkWidget *menu;
4212         gint num = 0, def_menu = 0;
4213
4214         accounts = account_get_list();
4215         g_return_val_if_fail(accounts != NULL, NULL);
4216
4217         hbox = gtk_hbox_new(FALSE, 0);
4218         optmenu = gtk_option_menu_new();
4219         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
4220         menu = gtk_menu_new();
4221
4222         for (; accounts != NULL; accounts = accounts->next, num++) {
4223                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
4224                 GtkWidget *menuitem;
4225                 gchar *name;
4226
4227                 if (ac == compose->account) def_menu = num;
4228
4229                 name = g_strdup_printf("%s: %s <%s>",
4230                                        ac->account_name, ac->name, ac->address);
4231                 MENUITEM_ADD(menu, menuitem, name, ac);
4232                 g_free(name);
4233                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
4234                                    GTK_SIGNAL_FUNC(account_activated),
4235                                    compose);
4236         }
4237
4238         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
4239         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
4240
4241         return hbox;
4242 }
4243
4244 static void compose_set_template_menu(Compose *compose)
4245 {
4246         GSList *tmpl_list, *cur;
4247         GtkWidget *menu;
4248         GtkWidget *item;
4249
4250         tmpl_list = template_get_config();
4251
4252         menu = gtk_menu_new();
4253
4254         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
4255                 Template *tmpl = (Template *)cur->data;
4256
4257                 item = gtk_menu_item_new_with_label(tmpl->name);
4258                 gtk_menu_append(GTK_MENU(menu), item);
4259                 gtk_signal_connect(GTK_OBJECT(item), "activate",
4260                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
4261                                    compose);
4262                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
4263                 gtk_widget_show(item);
4264         }
4265
4266         gtk_widget_show(menu);
4267         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
4268 }
4269
4270 void compose_reflect_prefs_all(void)
4271 {
4272         GList *cur;
4273         Compose *compose;
4274
4275         for (cur = compose_list; cur != NULL; cur = cur->next) {
4276                 compose = (Compose *)cur->data;
4277                 compose_set_template_menu(compose);
4278         }
4279 }
4280
4281 static void compose_template_apply(Compose *compose, const gchar *tmpl_str)
4282 {
4283         gchar *qmark;
4284         gchar *parsed_str;
4285
4286         if (!tmpl_str) return;
4287
4288         gtk_stext_freeze(GTK_TEXT(compose->text));
4289
4290         if (compose->replyinfo == NULL) {
4291                 MsgInfo dummyinfo;
4292
4293                 memset(&dummyinfo, 0, sizeof(MsgInfo));
4294                 parsed_str = compose_quote_fmt(compose, &dummyinfo, tmpl_str,
4295                                                NULL);
4296         } else {
4297                 if (prefs_common.quotemark && *prefs_common.quotemark)
4298                         qmark = prefs_common.quotemark;
4299                 else
4300                         qmark = "> ";
4301
4302                 parsed_str = compose_quote_fmt(compose, compose->replyinfo, tmpl_str,
4303                                                qmark);
4304         }
4305
4306         if (parsed_str && prefs_common.auto_sig)
4307                 compose_insert_sig(compose);
4308
4309         gtk_stext_thaw(GTK_TEXT(compose->text));
4310 }
4311
4312 static void compose_destroy(Compose *compose)
4313 {
4314         gint row;
4315         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4316         AttachInfo *ainfo;
4317
4318         /* NOTE: address_completion_end() does nothing with the window
4319          * however this may change. */
4320         address_completion_end(compose->window);
4321
4322         slist_free_strings(compose->to_list);
4323         g_slist_free(compose->to_list);
4324         slist_free_strings(compose->newsgroup_list);
4325         g_slist_free(compose->newsgroup_list);
4326         slist_free_strings(compose->header_list);
4327         g_slist_free(compose->header_list);
4328
4329         procmsg_msginfo_free(compose->targetinfo);
4330         procmsg_msginfo_free(compose->replyinfo);
4331
4332         g_free(compose->replyto);
4333         g_free(compose->cc);
4334         g_free(compose->bcc);
4335         g_free(compose->newsgroups);
4336         g_free(compose->followup_to);
4337
4338         g_free(compose->inreplyto);
4339         g_free(compose->references);
4340         g_free(compose->msgid);
4341         g_free(compose->boundary);
4342
4343         g_free(compose->exteditor_file);
4344
4345         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
4346              row++)
4347                 compose_attach_info_free(ainfo);
4348
4349         if (addressbook_get_target_compose() == compose)
4350                 addressbook_set_target_compose(NULL);
4351
4352         prefs_common.compose_width = compose->scrolledwin->allocation.width;
4353         prefs_common.compose_height = compose->window->allocation.height;
4354
4355         gtk_widget_destroy(compose->paned);
4356
4357         g_free(compose);
4358
4359         compose_list = g_list_remove(compose_list, compose);
4360 }
4361
4362 static void compose_attach_info_free(AttachInfo *ainfo)
4363 {
4364         g_free(ainfo->file);
4365         g_free(ainfo->content_type);
4366         g_free(ainfo->name);
4367         g_free(ainfo);
4368 }
4369
4370 static void compose_attach_remove_selected(Compose *compose)
4371 {
4372         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4373         AttachInfo *ainfo;
4374         gint row;
4375
4376         while (clist->selection != NULL) {
4377                 row = GPOINTER_TO_INT(clist->selection->data);
4378                 ainfo = gtk_clist_get_row_data(clist, row);
4379                 compose_attach_info_free(ainfo);
4380                 gtk_clist_remove(clist, row);
4381         }
4382 }
4383
4384 static struct _AttachProperty
4385 {
4386         GtkWidget *window;
4387         GtkWidget *mimetype_entry;
4388         GtkWidget *encoding_optmenu;
4389         GtkWidget *path_entry;
4390         GtkWidget *filename_entry;
4391         GtkWidget *ok_btn;
4392         GtkWidget *cancel_btn;
4393 } attach_prop;
4394
4395 static void compose_attach_property(Compose *compose)
4396 {
4397         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4398         AttachInfo *ainfo;
4399         gint row;
4400         GtkOptionMenu *optmenu;
4401         static gboolean cancelled;
4402
4403         if (!clist->selection) return;
4404         row = GPOINTER_TO_INT(clist->selection->data);
4405
4406         ainfo = gtk_clist_get_row_data(clist, row);
4407         if (!ainfo) return;
4408
4409         if (!attach_prop.window)
4410                 compose_attach_property_create(&cancelled);
4411         gtk_widget_grab_focus(attach_prop.ok_btn);
4412         gtk_widget_show(attach_prop.window);
4413         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
4414
4415         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
4416         if (ainfo->encoding == ENC_UNKNOWN)
4417                 gtk_option_menu_set_history(optmenu, ENC_BASE64);
4418         else
4419                 gtk_option_menu_set_history(optmenu, ainfo->encoding);
4420
4421         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
4422                            ainfo->content_type ? ainfo->content_type : "");
4423         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
4424                            ainfo->file ? ainfo->file : "");
4425         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
4426                            ainfo->name ? ainfo->name : "");
4427
4428         for (;;) {
4429                 gchar *text;
4430                 gchar *cnttype = NULL;
4431                 gchar *file = NULL;
4432                 off_t size = 0;
4433                 GtkWidget *menu;
4434                 GtkWidget *menuitem;
4435
4436                 cancelled = FALSE;
4437                 gtk_main();
4438
4439                 if (cancelled == TRUE) {
4440                         gtk_widget_hide(attach_prop.window);
4441                         break;
4442                 }
4443
4444                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
4445                 if (*text != '\0') {
4446                         gchar *p;
4447
4448                         text = g_strstrip(g_strdup(text));
4449                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
4450                                 cnttype = g_strdup(text);
4451                                 g_free(text);
4452                         } else {
4453                                 alertpanel_error(_("Invalid MIME type."));
4454                                 g_free(text);
4455                                 continue;
4456                         }
4457                 }
4458
4459                 menu = gtk_option_menu_get_menu(optmenu);
4460                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
4461                 ainfo->encoding = GPOINTER_TO_INT
4462                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
4463
4464                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
4465                 if (*text != '\0') {
4466                         if (is_file_exist(text) &&
4467                             (size = get_file_size(text)) > 0)
4468                                 file = g_strdup(text);
4469                         else {
4470                                 alertpanel_error
4471                                         (_("File doesn't exist or is empty."));
4472                                 g_free(cnttype);
4473                                 continue;
4474                         }
4475                 }
4476
4477                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
4478                 if (*text != '\0') {
4479                         g_free(ainfo->name);
4480                         ainfo->name = g_strdup(text);
4481                 }
4482
4483                 if (cnttype) {
4484                         g_free(ainfo->content_type);
4485                         ainfo->content_type = cnttype;
4486                 }
4487                 if (file) {
4488                         g_free(ainfo->file);
4489                         ainfo->file = file;
4490                 }
4491                 if (size)
4492                         ainfo->size = size;
4493
4494                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
4495                                    ainfo->content_type);
4496                 gtk_clist_set_text(clist, row, COL_SIZE,
4497                                    to_human_readable(ainfo->size));
4498                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
4499
4500                 gtk_widget_hide(attach_prop.window);
4501                 break;
4502         }
4503 }
4504
4505 #define SET_LABEL_AND_ENTRY(str, entry, top) \
4506 { \
4507         label = gtk_label_new(str); \
4508         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
4509                          GTK_FILL, 0, 0, 0); \
4510         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
4511  \
4512         entry = gtk_entry_new(); \
4513         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
4514                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
4515 }
4516
4517 static void compose_attach_property_create(gboolean *cancelled)
4518 {
4519         GtkWidget *window;
4520         GtkWidget *vbox;
4521         GtkWidget *table;
4522         GtkWidget *label;
4523         GtkWidget *mimetype_entry;
4524         GtkWidget *hbox;
4525         GtkWidget *optmenu;
4526         GtkWidget *optmenu_menu;
4527         GtkWidget *menuitem;
4528         GtkWidget *path_entry;
4529         GtkWidget *filename_entry;
4530         GtkWidget *hbbox;
4531         GtkWidget *ok_btn;
4532         GtkWidget *cancel_btn;
4533         GList     *mime_type_list, *strlist;
4534
4535         debug_print("Creating attach_property window...\n");
4536
4537         window = gtk_window_new(GTK_WINDOW_DIALOG);
4538         gtk_widget_set_usize(window, 480, -1);
4539         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
4540         gtk_window_set_title(GTK_WINDOW(window), _("Property"));
4541         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
4542         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
4543         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4544                            GTK_SIGNAL_FUNC(attach_property_delete_event),
4545                            cancelled);
4546         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
4547                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
4548                            cancelled);
4549
4550         vbox = gtk_vbox_new(FALSE, 8);
4551         gtk_container_add(GTK_CONTAINER(window), vbox);
4552
4553         table = gtk_table_new(4, 2, FALSE);
4554         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
4555         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
4556         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
4557
4558         label = gtk_label_new(_("MIME type")); 
4559         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
4560                          GTK_FILL, 0, 0, 0); 
4561         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
4562         mimetype_entry = gtk_combo_new(); 
4563         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
4564                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
4565                          
4566         /* stuff with list */
4567         mime_type_list = procmime_get_mime_type_list();
4568         strlist = NULL;
4569         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
4570                 MimeType *type = (MimeType *) mime_type_list->data;
4571                 strlist = g_list_append(strlist, 
4572                                 g_strdup_printf("%s/%s",
4573                                         type->type, type->sub_type));
4574         }
4575         
4576         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
4577
4578         for (mime_type_list = strlist; mime_type_list != NULL; 
4579                 mime_type_list = mime_type_list->next)
4580                 g_free(mime_type_list->data);
4581         g_list_free(strlist);
4582                          
4583         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
4584
4585         label = gtk_label_new(_("Encoding"));
4586         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
4587                          GTK_FILL, 0, 0, 0);
4588         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
4589
4590         hbox = gtk_hbox_new(FALSE, 0);
4591         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
4592                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
4593
4594         optmenu = gtk_option_menu_new();
4595         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
4596
4597         optmenu_menu = gtk_menu_new();
4598         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
4599         gtk_widget_set_sensitive(menuitem, FALSE);
4600         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
4601         gtk_widget_set_sensitive(menuitem, FALSE);
4602         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable", ENC_QUOTED_PRINTABLE);
4603         gtk_widget_set_sensitive(menuitem, FALSE);
4604         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
4605
4606         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
4607
4608         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
4609         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
4610
4611         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
4612                                 &cancel_btn, _("Cancel"), NULL, NULL);
4613         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
4614         gtk_widget_grab_default(ok_btn);
4615
4616         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
4617                            GTK_SIGNAL_FUNC(attach_property_ok),
4618                            cancelled);
4619         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
4620                            GTK_SIGNAL_FUNC(attach_property_cancel),
4621                            cancelled);
4622
4623         gtk_widget_show_all(vbox);
4624
4625         attach_prop.window           = window;
4626         attach_prop.mimetype_entry   = mimetype_entry;
4627         attach_prop.encoding_optmenu = optmenu;
4628         attach_prop.path_entry       = path_entry;
4629         attach_prop.filename_entry   = filename_entry;
4630         attach_prop.ok_btn           = ok_btn;
4631         attach_prop.cancel_btn       = cancel_btn;
4632 }
4633
4634 #undef SET_LABEL_AND_ENTRY
4635
4636 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
4637 {
4638         *cancelled = FALSE;
4639         gtk_main_quit();
4640 }
4641
4642 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
4643 {
4644         *cancelled = TRUE;
4645         gtk_main_quit();
4646 }
4647
4648 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
4649                                          gboolean *cancelled)
4650 {
4651         *cancelled = TRUE;
4652         gtk_main_quit();
4653
4654         return TRUE;
4655 }
4656
4657 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
4658                                         gboolean *cancelled)
4659 {
4660         if (event && event->keyval == GDK_Escape) {
4661                 *cancelled = TRUE;
4662                 gtk_main_quit();
4663         }
4664 }
4665
4666 static void compose_exec_ext_editor(Compose *compose)
4667 {
4668         gchar tmp[64];
4669         pid_t pid;
4670         gint pipe_fds[2];
4671
4672         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.%08x",
4673                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
4674
4675         if (pipe(pipe_fds) < 0) {
4676                 perror("pipe");
4677                 return;
4678         }
4679
4680         if ((pid = fork()) < 0) {
4681                 perror("fork");
4682                 return;
4683         }
4684
4685         if (pid != 0) {
4686                 /* close the write side of the pipe */
4687                 close(pipe_fds[1]);
4688
4689                 compose->exteditor_file    = g_strdup(tmp);
4690                 compose->exteditor_pid     = pid;
4691                 compose->exteditor_readdes = pipe_fds[0];
4692
4693                 compose_set_ext_editor_sensitive(compose, FALSE);
4694
4695                 compose->exteditor_tag =
4696                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
4697                                       compose_input_cb, compose);
4698         } else {        /* process-monitoring process */
4699                 pid_t pid_ed;
4700
4701                 if (setpgid(0, 0))
4702                         perror("setpgid");
4703
4704                 /* close the read side of the pipe */
4705                 close(pipe_fds[0]);
4706
4707                 if (compose_write_body_to_file(compose, tmp) < 0) {
4708                         fd_write(pipe_fds[1], "2\n", 2);
4709                         _exit(1);
4710                 }
4711
4712                 pid_ed = compose_exec_ext_editor_real(tmp);
4713                 if (pid_ed < 0) {
4714                         fd_write(pipe_fds[1], "1\n", 2);
4715                         _exit(1);
4716                 }
4717
4718                 /* wait until editor is terminated */
4719                 waitpid(pid_ed, NULL, 0);
4720
4721                 fd_write(pipe_fds[1], "0\n", 2);
4722
4723                 close(pipe_fds[1]);
4724                 _exit(0);
4725         }
4726 }
4727
4728 static gint compose_exec_ext_editor_real(const gchar *file)
4729 {
4730         static gchar *def_cmd = "emacs %s";
4731         gchar buf[1024];
4732         gchar *p;
4733         gchar **cmdline;
4734         pid_t pid;
4735
4736         g_return_val_if_fail(file != NULL, -1);
4737
4738         if ((pid = fork()) < 0) {
4739                 perror("fork");
4740                 return -1;
4741         }
4742
4743         if (pid != 0) return pid;
4744
4745         /* grandchild process */
4746
4747         if (setpgid(0, getppid()))
4748                 perror("setpgid");
4749
4750         if (prefs_common.ext_editor_cmd &&
4751             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
4752             *(p + 1) == 's' && !strchr(p + 2, '%')) {
4753                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
4754         } else {
4755                 if (prefs_common.ext_editor_cmd)
4756                         g_warning(_("External editor command line is invalid: `%s'\n"),
4757                                   prefs_common.ext_editor_cmd);
4758                 g_snprintf(buf, sizeof(buf), def_cmd, file);
4759         }
4760
4761         cmdline = g_strsplit(buf, " ", 1024);
4762         execvp(cmdline[0], cmdline);
4763
4764         perror("execvp");
4765         g_strfreev(cmdline);
4766
4767         _exit(1);
4768 }
4769
4770 static gboolean compose_ext_editor_kill(Compose *compose)
4771 {
4772         pid_t pgid = compose->exteditor_pid * -1;
4773         gint ret;
4774
4775         ret = kill(pgid, 0);
4776
4777         if (ret == 0 || (ret == -1 && EPERM == errno)) {
4778                 AlertValue val;
4779                 gchar *msg;
4780
4781                 msg = g_strdup_printf
4782                         (_("The external editor is still working.\n"
4783                            "Force terminating the process?\n"
4784                            "process group id: %d"), -pgid);
4785                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
4786                 g_free(msg);
4787
4788                 if (val == G_ALERTDEFAULT) {
4789                         gdk_input_remove(compose->exteditor_tag);
4790                         close(compose->exteditor_readdes);
4791
4792                         if (kill(pgid, SIGTERM) < 0) perror("kill");
4793                         waitpid(compose->exteditor_pid, NULL, 0);
4794
4795                         g_warning(_("Terminated process group id: %d"), -pgid);
4796                         g_warning(_("Temporary file: %s"),
4797                                   compose->exteditor_file);
4798
4799                         compose_set_ext_editor_sensitive(compose, TRUE);
4800
4801                         g_free(compose->exteditor_file);
4802                         compose->exteditor_file    = NULL;
4803                         compose->exteditor_pid     = -1;
4804                         compose->exteditor_readdes = -1;
4805                         compose->exteditor_tag     = -1;
4806                 } else
4807                         return FALSE;
4808         }
4809
4810         return TRUE;
4811 }
4812
4813 static void compose_input_cb(gpointer data, gint source,
4814                              GdkInputCondition condition)
4815 {
4816         gchar buf[3];
4817         Compose *compose = (Compose *)data;
4818         gint i = 0;
4819
4820         debug_print(_("Compose: input from monitoring process\n"));
4821
4822         gdk_input_remove(compose->exteditor_tag);
4823
4824         for (;;) {
4825                 if (read(source, &buf[i], 1) < 1) {
4826                         buf[0] = '3';
4827                         break;
4828                 }
4829                 if (buf[i] == '\n') {
4830                         buf[i] = '\0';
4831                         break;
4832                 }
4833                 i++;
4834                 if (i == sizeof(buf) - 1)
4835                         break;
4836         }
4837
4838         waitpid(compose->exteditor_pid, NULL, 0);
4839
4840         if (buf[0] == '0') {            /* success */
4841                 GtkSText *text = GTK_STEXT(compose->text);
4842
4843                 gtk_stext_freeze(text);
4844                 gtk_stext_set_point(text, 0);
4845                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
4846                 compose_insert_file(compose, compose->exteditor_file);
4847                 compose_changed_cb(NULL, compose);
4848                 gtk_stext_thaw(text);
4849
4850                 if (unlink(compose->exteditor_file) < 0)
4851                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
4852         } else if (buf[0] == '1') {     /* failed */
4853                 g_warning(_("Couldn't exec external editor\n"));
4854                 if (unlink(compose->exteditor_file) < 0)
4855                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
4856         } else if (buf[0] == '2') {
4857                 g_warning(_("Couldn't write to file\n"));
4858         } else if (buf[0] == '3') {
4859                 g_warning(_("Pipe read failed\n"));
4860         }
4861
4862         close(source);
4863
4864         compose_set_ext_editor_sensitive(compose, TRUE);
4865
4866         g_free(compose->exteditor_file);
4867         compose->exteditor_file    = NULL;
4868         compose->exteditor_pid     = -1;
4869         compose->exteditor_readdes = -1;
4870         compose->exteditor_tag     = -1;
4871 }
4872
4873 static void compose_set_ext_editor_sensitive(Compose *compose,
4874                                              gboolean sensitive)
4875 {
4876         GtkItemFactory *ifactory;
4877
4878         ifactory = gtk_item_factory_from_widget(compose->menubar);
4879
4880         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
4881         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
4882         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
4883                            sensitive);
4884         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
4885         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
4886         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
4887         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
4888         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
4889                            sensitive);
4890
4891         gtk_widget_set_sensitive(compose->text,          sensitive);
4892         gtk_widget_set_sensitive(compose->send_btn,      sensitive);
4893         gtk_widget_set_sensitive(compose->sendl_btn,     sensitive);
4894         gtk_widget_set_sensitive(compose->draft_btn,     sensitive);
4895         gtk_widget_set_sensitive(compose->insert_btn,    sensitive);
4896         gtk_widget_set_sensitive(compose->sig_btn,       sensitive);
4897         gtk_widget_set_sensitive(compose->exteditor_btn, sensitive);
4898         gtk_widget_set_sensitive(compose->linewrap_btn,  sensitive);
4899 }
4900
4901 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
4902 {
4903         gint cursor_pos;
4904
4905         cursor_pos = (text->cursor_pos_x - extra) / char_width;
4906         cursor_pos = MAX(cursor_pos, 0);
4907
4908         return cursor_pos;
4909 }
4910
4911 /* callback functions */
4912
4913 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
4914  * includes "non-client" (windows-izm) in calculation, so this calculation
4915  * may not be accurate.
4916  */
4917 static gboolean compose_edit_size_alloc(GtkEditable *widget,
4918                                         GtkAllocation *allocation,
4919                                         GtkSHRuler *shruler)
4920 {
4921         if (prefs_common.show_ruler) {
4922                 gint char_width;
4923                 gint line_width_in_chars;
4924
4925                 char_width = gtkut_get_font_width
4926                         (GTK_WIDGET(widget)->style->font);
4927                 line_width_in_chars =
4928                         (allocation->width - allocation->x) / char_width;
4929
4930                 /* got the maximum */
4931                 gtk_ruler_set_range(GTK_RULER(shruler),
4932                                     0.0, line_width_in_chars,
4933                                     calc_cursor_xpos(GTK_STEXT(widget),
4934                                                      allocation->x,
4935                                                      char_width),
4936                                     /*line_width_in_chars*/ char_width);
4937         }
4938
4939         return TRUE;
4940 }
4941
4942 static void toolbar_send_cb(GtkWidget *widget, gpointer data)
4943 {
4944         compose_send_cb(data, 0, NULL);
4945 }
4946
4947 static void toolbar_send_later_cb(GtkWidget *widget, gpointer data)
4948 {
4949         compose_send_later_cb(data, 0, NULL);
4950 }
4951
4952 static void toolbar_draft_cb(GtkWidget *widget, gpointer data)
4953 {
4954         compose_draft_cb(data, 0, NULL);
4955 }
4956
4957 static void toolbar_insert_cb(GtkWidget *widget, gpointer data)
4958 {
4959         compose_insert_file_cb(data, 0, NULL);
4960 }
4961
4962 static void toolbar_attach_cb(GtkWidget *widget, gpointer data)
4963 {
4964         compose_attach_cb(data, 0, NULL);
4965 }
4966
4967 static void toolbar_sig_cb(GtkWidget *widget, gpointer data)
4968 {
4969         Compose *compose = (Compose *)data;
4970
4971         compose_insert_sig(compose);
4972 }
4973
4974 static void toolbar_ext_editor_cb(GtkWidget *widget, gpointer data)
4975 {
4976         Compose *compose = (Compose *)data;
4977
4978         compose_exec_ext_editor(compose);
4979 }
4980
4981 static void toolbar_linewrap_cb(GtkWidget *widget, gpointer data)
4982 {
4983         Compose *compose = (Compose *)data;
4984
4985         compose_wrap_line(compose);
4986 }
4987
4988 static void toolbar_address_cb(GtkWidget *widget, gpointer data)
4989 {
4990         compose_address_cb(data, 0, NULL);
4991 }
4992
4993 static void select_account(Compose * compose, PrefsAccount * ac)
4994 {
4995         compose->account = ac;
4996         compose_set_title(compose);
4997
4998 #if 0 /* NEW COMPOSE GUI */
4999                 if (ac->protocol == A_NNTP) {
5000                         GtkItemFactory *ifactory;
5001                         GtkWidget *menuitem;
5002
5003                         ifactory = gtk_item_factory_from_widget(compose->menubar);
5004                         menu_set_sensitive(ifactory,
5005                                            "/Message/Followup to", TRUE);
5006                         gtk_widget_show(compose->newsgroups_hbox);
5007                         gtk_widget_show(compose->newsgroups_entry);
5008                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5009                                                   1, 4);
5010
5011                         compose->use_to = FALSE;
5012                         compose->use_cc = FALSE;
5013
5014                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
5015                         gtk_check_menu_item_set_active
5016                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5017
5018                         menu_set_sensitive(ifactory,
5019                                            "/Message/To", TRUE);
5020                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
5021                         gtk_check_menu_item_set_active
5022                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5023
5024                         gtk_widget_hide(compose->to_hbox);
5025                         gtk_widget_hide(compose->to_entry);
5026                         gtk_widget_hide(compose->cc_hbox);
5027                         gtk_widget_hide(compose->cc_entry);
5028                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5029                                                   0, 0);
5030                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5031                                                   3, 0);
5032                 }
5033                 else {
5034                         GtkItemFactory *ifactory;
5035                         GtkWidget *menuitem;
5036
5037                         ifactory = gtk_item_factory_from_widget(compose->menubar);
5038                         menu_set_sensitive(ifactory,
5039                                            "/Message/Followup to", FALSE);
5040                         gtk_entry_set_text(GTK_ENTRY(compose->newsgroups_entry), "");
5041                         gtk_widget_hide(compose->newsgroups_hbox);
5042                         gtk_widget_hide(compose->newsgroups_entry);
5043                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5044                                                   1, 0);
5045
5046                         compose->use_to = TRUE;
5047                         compose->use_cc = TRUE;
5048
5049                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
5050                         gtk_check_menu_item_set_active
5051                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5052                         menu_set_sensitive(ifactory,
5053                                            "/Message/To", FALSE);
5054                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
5055                         gtk_check_menu_item_set_active
5056                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5057                         gtk_widget_show(compose->to_hbox);
5058                         gtk_widget_show(compose->to_entry);
5059                         gtk_widget_show(compose->cc_hbox);
5060                         gtk_widget_show(compose->cc_entry);
5061
5062                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5063                                                   0, 4);
5064                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5065                                                   3, 4);
5066                 }
5067                 gtk_widget_queue_resize(compose->table_vbox);
5068 #endif
5069 }
5070
5071 static void account_activated(GtkMenuItem *menuitem, gpointer data)
5072 {
5073         Compose *compose = (Compose *)data;
5074
5075         PrefsAccount *ac;
5076
5077         ac = (PrefsAccount *)gtk_object_get_user_data(GTK_OBJECT(menuitem));
5078         g_return_if_fail(ac != NULL);
5079
5080         if (ac != compose->account)
5081                 select_account(compose, ac);
5082 }
5083
5084 static void attach_selected(GtkCList *clist, gint row, gint column,
5085                             GdkEvent *event, gpointer data)
5086 {
5087         Compose *compose = (Compose *)data;
5088
5089         if (event && event->type == GDK_2BUTTON_PRESS)
5090                 compose_attach_property(compose);
5091 }
5092
5093 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
5094                                   gpointer data)
5095 {
5096         Compose *compose = (Compose *)data;
5097         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5098         gint row, column;
5099
5100         if (!event) return;
5101
5102         if (event->button == 3) {
5103                 if ((clist->selection && !clist->selection->next) ||
5104                     !clist->selection) {
5105                         gtk_clist_unselect_all(clist);
5106                         if (gtk_clist_get_selection_info(clist,
5107                                                          event->x, event->y,
5108                                                          &row, &column)) {
5109                                 gtk_clist_select_row(clist, row, column);
5110                                 gtkut_clist_set_focus_row(clist, row);
5111                         }
5112                 }
5113                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
5114                                NULL, NULL, event->button, event->time);
5115         }
5116 }
5117
5118 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
5119                                gpointer data)
5120 {
5121         Compose *compose = (Compose *)data;
5122
5123         if (!event) return;
5124
5125         switch (event->keyval) {
5126         case GDK_Delete:
5127                 compose_attach_remove_selected(compose);
5128                 break;
5129         }
5130 }
5131
5132 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
5133 {
5134         Compose *compose = (Compose *)data;
5135         gint val;
5136
5137         val = compose_send(compose);
5138
5139         if (val == 0) gtk_widget_destroy(compose->window);
5140 }
5141
5142 static void compose_send_later_cb(gpointer data, guint action,
5143                                   GtkWidget *widget)
5144 {
5145         Compose *compose = (Compose *)data;
5146         gchar tmp[22];
5147         gboolean recipient_found;
5148         GSList *list;
5149
5150         if(!compose_check_for_valid_recipient(compose)) {
5151                 alertpanel_error(_("Recipient is not specified."));
5152                 return;
5153         }
5154
5155         g_snprintf(tmp, 22, "%s%ctmpmsg%d",
5156                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
5157
5158         if (prefs_common.linewrap_at_send)
5159                 compose_wrap_line_all(compose);
5160
5161         if (compose_write_to_file(compose, tmp, FALSE) < 0 ||
5162             compose_queue(compose, tmp) < 0) {
5163                 alertpanel_error(_("Can't queue the message."));
5164                 return;
5165         }
5166
5167         if (prefs_common.savemsg) {
5168                 if (compose_save_to_outbox(compose, tmp) < 0)
5169                         alertpanel_error
5170                                 (_("Can't save the message to outbox."));
5171         }
5172
5173         if (unlink(tmp) < 0)
5174                 FILE_OP_ERROR(tmp, "unlink");
5175
5176         gtk_widget_destroy(compose->window);
5177 }
5178
5179 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
5180 {
5181         Compose *compose = (Compose *)data;
5182         FolderItem *draft;
5183         gchar *tmp;
5184
5185         draft = folder_get_default_draft();
5186
5187         tmp = g_strdup_printf("%s%cdraft.%d", g_get_tmp_dir(),
5188                               G_DIR_SEPARATOR, (gint)compose);
5189
5190         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
5191                 g_free(tmp);
5192                 return;
5193         }
5194
5195         folder_item_scan(draft);
5196         if (folder_item_add_msg(draft, tmp, TRUE) < 0) {
5197                 unlink(tmp);
5198                 g_free(tmp);
5199                 return;
5200         }
5201         g_free(tmp);
5202
5203         if (compose->mode == COMPOSE_REEDIT) {
5204                 compose_remove_reedit_target(compose);
5205                 if (compose->targetinfo &&
5206                     compose->targetinfo->folder != draft)
5207                         folderview_update_item(compose->targetinfo->folder,
5208                                                TRUE);
5209         }
5210
5211         folder_item_scan(draft);
5212         folderview_update_item(draft, TRUE);
5213
5214         gtk_widget_destroy(compose->window);
5215 }
5216
5217 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
5218 {
5219         Compose *compose = (Compose *)data;
5220         GList *file_list;
5221
5222         file_list = filesel_select_multiple_files(_("Select file"), NULL);
5223
5224         if (file_list) {
5225                 GList *tmp;
5226
5227                 for ( tmp = file_list; tmp; tmp = tmp->next) {
5228                         gchar *file = (gchar *) tmp->data;
5229                         compose_attach_append(compose, file, MIME_UNKNOWN);
5230                         g_free(file);
5231                 }
5232                 g_list_free(file_list);
5233         }               
5234 }
5235
5236 static void compose_insert_file_cb(gpointer data, guint action,
5237                                    GtkWidget *widget)
5238 {
5239         Compose *compose = (Compose *)data;
5240         GList *file_list;
5241
5242         file_list = filesel_select_multiple_files(_("Select file"), NULL);
5243
5244         if (file_list) {
5245                 GList *tmp;
5246
5247                 for ( tmp = file_list; tmp; tmp = tmp->next) {
5248                         gchar *file = (gchar *) tmp->data;
5249                         compose_insert_file(compose, file);
5250                         g_free(file);
5251                 }
5252                 g_list_free(file_list);
5253         }
5254 }
5255
5256 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
5257                               gpointer data)
5258 {
5259         compose_close_cb(data, 0, NULL);
5260         return TRUE;
5261 }
5262
5263 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
5264 {
5265         Compose *compose = (Compose *)data;
5266         AlertValue val;
5267
5268         if (compose->exteditor_tag != -1) {
5269                 if (!compose_ext_editor_kill(compose))
5270                         return;
5271         }
5272
5273         if (compose->modified) {
5274                 val = alertpanel(_("Discard message"),
5275                                  _("This message has been modified. discard it?"),
5276                                  _("Discard"), _("to Draft"), _("Cancel"));
5277
5278                 switch (val) {
5279                 case G_ALERTDEFAULT:
5280                         break;
5281                 case G_ALERTALTERNATE:
5282                         compose_draft_cb(data, 0, NULL);
5283                         return;
5284                 default:
5285                         return;
5286                 }
5287         }
5288 #if USE_PSPELL
5289         if (compose->gtkpspell) {
5290                 gtkpspell_detach(compose->gtkpspell);
5291                 compose->gtkpspell = gtkpspell_delete(compose->gtkpspell);
5292         }
5293 #endif
5294         gtk_widget_destroy(compose->window);
5295 }
5296
5297 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
5298 {
5299         Compose *compose = (Compose *)data;
5300
5301         addressbook_open(compose);
5302 }
5303
5304 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
5305 {
5306         Compose *compose = (Compose *)data;
5307         Template *tmpl;
5308
5309         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
5310         g_return_if_fail(tmpl != NULL);
5311
5312         compose_template_apply(compose, tmpl->value);
5313 }
5314
5315 static void compose_ext_editor_cb(gpointer data, guint action,
5316                                   GtkWidget *widget)
5317 {
5318         Compose *compose = (Compose *)data;
5319
5320         compose_exec_ext_editor(compose);
5321 }
5322
5323 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
5324 {
5325         compose_destroy(compose);
5326 }
5327
5328 static void compose_cut_cb(Compose *compose)
5329 {
5330         if (compose->focused_editable &&
5331             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5332                 gtk_editable_cut_clipboard
5333                         (GTK_EDITABLE(compose->focused_editable));
5334 }
5335
5336 static void compose_copy_cb(Compose *compose)
5337 {
5338         if (compose->focused_editable &&
5339             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5340                 gtk_editable_copy_clipboard
5341                         (GTK_EDITABLE(compose->focused_editable));
5342 }
5343
5344 static void compose_paste_cb(Compose *compose)
5345 {
5346         if (compose->focused_editable &&
5347             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5348                 gtk_editable_paste_clipboard
5349                         (GTK_EDITABLE(compose->focused_editable));
5350 }
5351
5352 static void compose_allsel_cb(Compose *compose)
5353 {
5354         if (compose->focused_editable &&
5355             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5356                 gtk_editable_select_region
5357                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
5358 }
5359
5360 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
5361 {
5362         if (GTK_IS_EDITABLE(widget))
5363                 compose->focused_editable = widget;
5364 }
5365
5366 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
5367 {
5368         if (compose->modified == FALSE) {
5369                 compose->modified = TRUE;
5370                 compose_set_title(compose);
5371         }
5372 }
5373
5374 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
5375                                     Compose *compose)
5376 {
5377         gtk_stext_set_point(GTK_STEXT(widget),
5378                            gtk_editable_get_position(GTK_EDITABLE(widget)));
5379 }
5380
5381 #if 0
5382 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
5383                                  Compose *compose)
5384 {
5385         gtk_stext_set_point(GTK_STEXT(widget),
5386                            gtk_editable_get_position(GTK_EDITABLE(widget)));
5387 }
5388 #endif
5389
5390 #if 0 /* NEW COMPOSE GUI */
5391 static void compose_toggle_to_cb(gpointer data, guint action,
5392                                  GtkWidget *widget)
5393 {
5394         Compose *compose = (Compose *)data;
5395
5396         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5397                 gtk_widget_show(compose->to_hbox);
5398                 gtk_widget_show(compose->to_entry);
5399                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
5400                 compose->use_to = TRUE;
5401         } else {
5402                 gtk_widget_hide(compose->to_hbox);
5403                 gtk_widget_hide(compose->to_entry);
5404                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
5405                 gtk_widget_queue_resize(compose->table_vbox);
5406                 compose->use_to = FALSE;
5407         }
5408
5409         if (addressbook_get_target_compose() == compose)
5410                 addressbook_set_target_compose(compose);
5411 }
5412
5413 static void compose_toggle_cc_cb(gpointer data, guint action,
5414                                  GtkWidget *widget)
5415 {
5416         Compose *compose = (Compose *)data;
5417
5418         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5419                 gtk_widget_show(compose->cc_hbox);
5420                 gtk_widget_show(compose->cc_entry);
5421                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
5422                 compose->use_cc = TRUE;
5423         } else {
5424                 gtk_widget_hide(compose->cc_hbox);
5425                 gtk_widget_hide(compose->cc_entry);
5426                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
5427                 gtk_widget_queue_resize(compose->table_vbox);
5428                 compose->use_cc = FALSE;
5429         }
5430
5431         if (addressbook_get_target_compose() == compose)
5432                 addressbook_set_target_compose(compose);
5433 }
5434
5435 static void compose_toggle_bcc_cb(gpointer data, guint action,
5436                                   GtkWidget *widget)
5437 {
5438         Compose *compose = (Compose *)data;
5439
5440         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5441                 gtk_widget_show(compose->bcc_hbox);
5442                 gtk_widget_show(compose->bcc_entry);
5443                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
5444                 compose->use_bcc = TRUE;
5445         } else {
5446                 gtk_widget_hide(compose->bcc_hbox);
5447                 gtk_widget_hide(compose->bcc_entry);
5448                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
5449                 gtk_widget_queue_resize(compose->table_vbox);
5450                 compose->use_bcc = FALSE;
5451         }
5452
5453         if (addressbook_get_target_compose() == compose)
5454                 addressbook_set_target_compose(compose);
5455 }
5456
5457 static void compose_toggle_replyto_cb(gpointer data, guint action,
5458                                       GtkWidget *widget)
5459 {
5460         Compose *compose = (Compose *)data;
5461
5462         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5463                 gtk_widget_show(compose->reply_hbox);
5464                 gtk_widget_show(compose->reply_entry);
5465                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
5466                 compose->use_replyto = TRUE;
5467         } else {
5468                 gtk_widget_hide(compose->reply_hbox);
5469                 gtk_widget_hide(compose->reply_entry);
5470                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
5471                 gtk_widget_queue_resize(compose->table_vbox);
5472                 compose->use_replyto = FALSE;
5473         }
5474 }
5475
5476 static void compose_toggle_followupto_cb(gpointer data, guint action,
5477                                          GtkWidget *widget)
5478 {
5479         Compose *compose = (Compose *)data;
5480
5481         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5482                 gtk_widget_show(compose->followup_hbox);
5483                 gtk_widget_show(compose->followup_entry);
5484                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
5485                 compose->use_followupto = TRUE;
5486         } else {
5487                 gtk_widget_hide(compose->followup_hbox);
5488                 gtk_widget_hide(compose->followup_entry);
5489                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
5490                 gtk_widget_queue_resize(compose->table_vbox);
5491                 compose->use_followupto = FALSE;
5492         }
5493 }
5494
5495 static void compose_toggle_attach_cb(gpointer data, guint action,
5496                                      GtkWidget *widget)
5497 {
5498         Compose *compose = (Compose *)data;
5499
5500         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5501                 gtk_widget_ref(compose->edit_vbox);
5502
5503                 gtk_container_remove(GTK_CONTAINER(compose->vbox2),
5504                                      compose->edit_vbox);
5505                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
5506                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
5507                                    TRUE, TRUE, 0);
5508                 gtk_widget_show(compose->paned);
5509
5510                 gtk_widget_unref(compose->edit_vbox);
5511                 gtk_widget_unref(compose->paned);
5512
5513                 compose->use_attach = TRUE;
5514         } else {
5515                 gtk_widget_ref(compose->paned);
5516                 gtk_widget_ref(compose->edit_vbox);
5517
5518                 gtk_container_remove(GTK_CONTAINER(compose->vbox2),
5519                                      compose->paned);
5520                 gtk_container_remove(GTK_CONTAINER(compose->paned),
5521                                      compose->edit_vbox);
5522                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
5523                                    compose->edit_vbox, TRUE, TRUE, 0);
5524
5525                 gtk_widget_unref(compose->edit_vbox);
5526
5527                 compose->use_attach = FALSE;
5528         }
5529 }
5530 #endif
5531
5532 #if USE_GPGME
5533 static void compose_toggle_sign_cb(gpointer data, guint action,
5534                                    GtkWidget *widget)
5535 {
5536         Compose *compose = (Compose *)data;
5537
5538         if (GTK_CHECK_MENU_ITEM(widget)->active)
5539                 compose->use_signing = TRUE;
5540         else
5541                 compose->use_signing = FALSE;
5542 }
5543
5544 static void compose_toggle_encrypt_cb(gpointer data, guint action,
5545                                       GtkWidget *widget)
5546 {
5547         Compose *compose = (Compose *)data;
5548
5549         if (GTK_CHECK_MENU_ITEM(widget)->active)
5550                 compose->use_encryption = TRUE;
5551         else
5552                 compose->use_encryption = FALSE;
5553 }
5554 #endif /* USE_GPGME */
5555
5556 static void compose_toggle_ruler_cb(gpointer data, guint action,
5557                                     GtkWidget *widget)
5558 {
5559         Compose *compose = (Compose *)data;
5560
5561         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5562                 gtk_widget_show(compose->ruler_hbox);
5563                 prefs_common.show_ruler = TRUE;
5564         } else {
5565                 gtk_widget_hide(compose->ruler_hbox);
5566                 gtk_widget_queue_resize(compose->edit_vbox);
5567                 prefs_common.show_ruler = FALSE;
5568         }
5569 }
5570
5571 static void compose_attach_drag_received_cb (GtkWidget          *widget,
5572                                              GdkDragContext     *drag_context,
5573                                              gint                x,
5574                                              gint                y,
5575                                              GtkSelectionData   *data,
5576                                              guint               info,
5577                                              guint               time,
5578                                              gpointer            user_data)
5579 {
5580         Compose *compose = (Compose *)user_data;
5581         GList *list, *tmp;
5582
5583         list = uri_list_extract_filenames((const gchar *)data->data);
5584         for (tmp = list; tmp != NULL; tmp = tmp->next)
5585                 compose_attach_append(compose, (const gchar *)tmp->data,
5586                                       MIME_UNKNOWN);
5587         list_free_strings(list);
5588         g_list_free(list);
5589 }
5590
5591 static void compose_insert_drag_received_cb (GtkWidget          *widget,
5592                                              GdkDragContext     *drag_context,
5593                                              gint                x,
5594                                              gint                y,
5595                                              GtkSelectionData   *data,
5596                                              guint               info,
5597                                              guint               time,
5598                                              gpointer            user_data)
5599 {
5600         Compose *compose = (Compose *)user_data;
5601         GList *list, *tmp;
5602
5603         list = uri_list_extract_filenames((const gchar *)data->data);
5604         for (tmp = list; tmp != NULL; tmp = tmp->next)
5605                 compose_insert_file(compose, (const gchar *)tmp->data);
5606         list_free_strings(list);
5607         g_list_free(list);
5608 }
5609
5610 #if 0 /* NEW COMPOSE GUI */
5611 static void to_activated(GtkWidget *widget, Compose *compose)
5612 {
5613         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
5614                 gtk_widget_grab_focus(compose->newsgroups_entry);
5615         else
5616                 gtk_widget_grab_focus(compose->subject_entry);
5617 }
5618
5619 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
5620 {
5621         gtk_widget_grab_focus(compose->subject_entry);
5622 }
5623
5624 static void subject_activated(GtkWidget *widget, Compose *compose)
5625 {
5626         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
5627                 gtk_widget_grab_focus(compose->cc_entry);
5628         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
5629                 gtk_widget_grab_focus(compose->bcc_entry);
5630         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
5631                 gtk_widget_grab_focus(compose->reply_entry);
5632         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
5633                 gtk_widget_grab_focus(compose->followup_entry);
5634         else
5635                 gtk_widget_grab_focus(compose->text);
5636 }
5637
5638 static void cc_activated(GtkWidget *widget, Compose *compose)
5639 {
5640         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
5641                 gtk_widget_grab_focus(compose->bcc_entry);
5642         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
5643                 gtk_widget_grab_focus(compose->reply_entry);
5644         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
5645                 gtk_widget_grab_focus(compose->followup_entry);
5646         else
5647                 gtk_widget_grab_focus(compose->text);
5648 }
5649
5650 static void bcc_activated(GtkWidget *widget, Compose *compose)
5651 {
5652         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
5653                 gtk_widget_grab_focus(compose->reply_entry);
5654         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
5655                 gtk_widget_grab_focus(compose->followup_entry);
5656         else
5657                 gtk_widget_grab_focus(compose->text);
5658 }
5659
5660 static void replyto_activated(GtkWidget *widget, Compose *compose)
5661 {
5662         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
5663                 gtk_widget_grab_focus(compose->followup_entry);
5664         else
5665                 gtk_widget_grab_focus(compose->text);
5666 }
5667
5668 static void followupto_activated(GtkWidget *widget, Compose *compose)
5669 {
5670         gtk_widget_grab_focus(compose->text);
5671 }
5672 #endif
5673
5674 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
5675                                              GtkWidget *widget)
5676 {
5677         Compose *compose = (Compose *)data;
5678
5679         if (GTK_CHECK_MENU_ITEM(widget)->active)
5680                 compose->return_receipt = TRUE;
5681         else
5682                 compose->return_receipt = FALSE;
5683 }
5684
5685 static void template_apply_cb(gchar *s, gpointer data)
5686 {
5687         Compose *compose = (Compose*)data;
5688         GtkSText *text = GTK_STEXT(compose->text);
5689         gchar *quote_str;
5690         gchar *qmark;
5691         gchar *parsed_text;
5692         gchar *tmpl;
5693         gchar *old_tmpl = s;
5694
5695         if(!s) return;
5696         
5697         if(compose->replyinfo == NULL) {
5698                 gtk_stext_freeze(text);
5699                 gtk_stext_set_point(text, 0);
5700                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5701                 gtk_stext_insert(text, NULL, NULL, NULL, s, -1);
5702                 gtk_stext_thaw(text);
5703                 g_free(old_tmpl);
5704                 return;
5705         }
5706
5707         parsed_text = g_new(gchar, strlen(s)*2 + 1);
5708         tmpl = parsed_text;
5709         while(*s) {
5710                 if (*s == '\n') {
5711                         *parsed_text++ = '\\';
5712                         *parsed_text++ = 'n';
5713                         s++;
5714                 } else {
5715                         *parsed_text++ = *s++;
5716                 }
5717         }
5718         *parsed_text = '\0';
5719
5720         if (prefs_common.quotemark && *prefs_common.quotemark)
5721                 qmark = prefs_common.quotemark;
5722         else
5723                 qmark = "> ";
5724
5725         quote_str = compose_quote_fmt(compose, compose->replyinfo, tmpl, qmark);
5726         if (quote_str != NULL) {
5727                 gtk_stext_freeze(text);
5728                 gtk_stext_set_point(text, 0);
5729                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5730                 gtk_stext_insert(text, NULL, NULL, NULL, quote_str, -1);
5731                 gtk_stext_thaw(text);
5732         }
5733
5734         g_free(old_tmpl);
5735         g_free(tmpl);
5736 }
5737
5738 static void template_select_cb(gpointer data, guint action,
5739                                GtkWidget *widget)
5740 {
5741         template_select(&template_apply_cb, data);
5742 }
5743
5744 void compose_headerentry_key_press_event_cb(GtkWidget *entry, GdkEventKey *event, compose_headerentry *headerentry) {
5745         if((g_slist_length(headerentry->compose->header_list) > 0) &&
5746             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
5747             !(event->state & GDK_MODIFIER_MASK) &&
5748             (event->keyval == GDK_BackSpace) &&
5749             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
5750                 gtk_container_remove(GTK_CONTAINER(headerentry->compose->header_table), headerentry->combo);
5751                 gtk_container_remove(GTK_CONTAINER(headerentry->compose->header_table), headerentry->entry);
5752                 headerentry->compose->header_list = g_slist_remove(headerentry->compose->header_list, headerentry);
5753                 g_free(headerentry);
5754         }
5755 }
5756
5757 void compose_headerentry_changed_cb(GtkWidget *entry, compose_headerentry *headerentry) {
5758         if(strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
5759                 headerentry->compose->header_list = g_slist_append(headerentry->compose->header_list, headerentry);
5760                 compose_create_header_entry(headerentry->compose);
5761                 gtk_signal_disconnect_by_func(GTK_OBJECT(entry), GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
5762         }
5763 }