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