0.9.0claws84
[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                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3488                         procmime_get_encoding_str(encoding));
3489                 fputc('\n', fp);
3490         }
3491
3492         /* write body */
3493         len = strlen(buf);
3494         if (encoding == ENC_BASE64) {
3495                 gchar outbuf[B64_BUFFSIZE];
3496                 gint i, l;
3497
3498                 for (i = 0; i < len; i += B64_LINE_SIZE) {
3499                         l = MIN(B64_LINE_SIZE, len - i);
3500                         base64_encode(outbuf, buf + i, l);
3501                         fputs(outbuf, fp);
3502                         fputc('\n', fp);
3503                 }
3504         } else if (encoding == ENC_QUOTED_PRINTABLE) {
3505                 gchar *outbuf;
3506                 size_t outlen;
3507
3508                 outbuf = g_malloc(len * 4);
3509                 qp_encode_line(outbuf, buf);
3510                 outlen = strlen(outbuf);
3511                 if (fwrite(outbuf, sizeof(gchar), outlen, fp) != outlen) {
3512                         FILE_OP_ERROR(file, "fwrite");
3513                         fclose(fp);
3514                         unlink(file);
3515                         g_free(outbuf);
3516                         g_free(buf);
3517                         return -1;
3518                 }
3519                 g_free(outbuf);
3520         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
3521                 FILE_OP_ERROR(file, "fwrite");
3522                 fclose(fp);
3523                 unlink(file);
3524                 g_free(buf);
3525                 return -1;
3526         }
3527         g_free(buf);
3528
3529         if (compose_use_attach(compose))
3530                 compose_write_attach(compose, fp);
3531
3532         if (fclose(fp) == EOF) {
3533                 FILE_OP_ERROR(file, "fclose");
3534                 unlink(file);
3535                 return -1;
3536         }
3537
3538 #if USE_GPGME
3539         if (is_draft) {
3540                 uncanonicalize_file_replace(file);
3541                 return 0;
3542         }
3543
3544         if ((compose->use_signing && !compose->gnupg_mode) ||
3545             compose->use_encryption) {
3546                 if (canonicalize_file_replace(file) < 0) {
3547                         unlink(file);
3548                         return -1;
3549                 }
3550         }
3551
3552         if (compose->use_signing && !compose->gnupg_mode) {
3553                 GSList *key_list;
3554
3555                 if (compose_create_signers_list(compose, &key_list) < 0 ||
3556                     rfc2015_sign(file, key_list) < 0) {
3557                         unlink(file);
3558                         return -1;
3559                 }
3560         }
3561         if (compose->use_encryption) {
3562                 if (rfc2015_encrypt(file, compose->to_list,
3563                                     compose->gnupg_mode) < 0) {
3564                         unlink(file);
3565                         return -1;
3566                 }
3567         }
3568 #endif /* USE_GPGME */
3569
3570         uncanonicalize_file_replace(file);
3571
3572         return 0;
3573 }
3574
3575 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3576 {
3577         FILE *fp;
3578         size_t len;
3579         gchar *chars;
3580
3581         if ((fp = fopen(file, "wb")) == NULL) {
3582                 FILE_OP_ERROR(file, "fopen");
3583                 return -1;
3584         }
3585
3586         /* chmod for security */
3587         if (change_file_mode_rw(fp, file) < 0) {
3588                 FILE_OP_ERROR(file, "chmod");
3589                 g_warning("can't change file mode\n");
3590         }
3591
3592         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3593
3594         /* write body */
3595         len = strlen(chars);
3596         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3597                 FILE_OP_ERROR(file, "fwrite");
3598                 g_free(chars);
3599                 fclose(fp);
3600                 unlink(file);
3601                 return -1;
3602         }
3603
3604         g_free(chars);
3605
3606         if (fclose(fp) == EOF) {
3607                 FILE_OP_ERROR(file, "fclose");
3608                 unlink(file);
3609                 return -1;
3610         }
3611         return 0;
3612 }
3613
3614 static gint compose_remove_reedit_target(Compose *compose)
3615 {
3616         FolderItem *item;
3617         MsgInfo *msginfo = compose->targetinfo;
3618
3619         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3620         if (!msginfo) return -1;
3621
3622         item = msginfo->folder;
3623         g_return_val_if_fail(item != NULL, -1);
3624
3625         if (procmsg_msg_exist(msginfo) &&
3626             (item->stype == F_DRAFT || item->stype == F_QUEUE 
3627              || msginfo == compose->autosaved_draft)) {
3628                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3629                         g_warning("can't remove the old message\n");
3630                         return -1;
3631                 }
3632         }
3633
3634         return 0;
3635 }
3636
3637 void compose_remove_draft(Compose *compose)
3638 {
3639         FolderItem *drafts;
3640         MsgInfo *msginfo = compose->targetinfo;
3641         drafts = account_get_special_folder(compose->account, F_DRAFT);
3642
3643         if (procmsg_msg_exist(msginfo)) {
3644                 folder_item_remove_msg(drafts, msginfo->msgnum);
3645         }
3646
3647 }
3648
3649 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3650 {
3651         return compose_queue_sub (compose, msgnum, item, FALSE);
3652 }
3653 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
3654 {
3655         FolderItem *queue;
3656         gchar *tmp, *tmp2;
3657         FILE *fp, *src_fp;
3658         GSList *cur;
3659         gchar buf[BUFFSIZE];
3660         gint num;
3661         static gboolean lock = FALSE;
3662         PrefsAccount *mailac = NULL, *newsac = NULL;
3663         
3664         debug_print("queueing message...\n");
3665         g_return_val_if_fail(compose->account != NULL, -1);
3666
3667         lock = TRUE;
3668         
3669         if (compose_check_entries(compose, check_subject) == FALSE) {
3670                 lock = FALSE;
3671                 return -1;
3672         }
3673
3674         if (!compose->to_list && !compose->newsgroup_list) {
3675                 g_warning("can't get recipient list.");
3676                 lock = FALSE;
3677                 return -1;
3678         }
3679
3680         if (compose->to_list) {
3681                 if (compose->account->protocol != A_NNTP)
3682                         mailac = compose->account;
3683                 else if (cur_account && cur_account->protocol != A_NNTP)
3684                         mailac = cur_account;
3685                 else if (!(mailac = compose_current_mail_account())) {
3686                         lock = FALSE;
3687                         alertpanel_error(_("No account for sending mails available!"));
3688                         return -1;
3689                 }
3690         }
3691
3692         if (compose->newsgroup_list) {
3693                 if (compose->account->protocol == A_NNTP)
3694                         newsac = compose->account;
3695                 else if (!newsac->protocol != A_NNTP) {
3696                         lock = FALSE;
3697                         alertpanel_error(_("No account for posting news available!"));
3698                         return -1;
3699                 }                       
3700         }
3701
3702         if (prefs_common.linewrap_at_send)
3703                 compose_wrap_line_all(compose);
3704                         
3705         /* write to temporary file */
3706         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3707                                       G_DIR_SEPARATOR, (gint)compose);
3708
3709         if (compose->redirect_filename != NULL) {
3710                 if (compose_redirect_write_to_file(compose, tmp2) < 0) {
3711                         unlink(tmp2);
3712                         lock = FALSE;
3713                         return -1;
3714                 }
3715         }
3716         else {
3717                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3718                         unlink(tmp2);
3719                         lock = FALSE;
3720                         return -1;
3721                 }
3722         }
3723
3724         /* add queue header */
3725         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3726                               G_DIR_SEPARATOR, (gint)compose);
3727         if ((fp = fopen(tmp, "wb")) == NULL) {
3728                 FILE_OP_ERROR(tmp, "fopen");
3729                 g_free(tmp);
3730                 return -1;
3731         }
3732         if ((src_fp = fopen(tmp2, "rb")) == NULL) {
3733                 FILE_OP_ERROR(tmp2, "fopen");
3734                 fclose(fp);
3735                 unlink(tmp);
3736                 g_free(tmp);
3737                 unlink(tmp2);
3738                 g_free(tmp2);
3739                 return -1;
3740         }
3741         if (change_file_mode_rw(fp, tmp) < 0) {
3742                 FILE_OP_ERROR(tmp, "chmod");
3743                 g_warning("can't change file mode\n");
3744         }
3745
3746         /* queueing variables */
3747         fprintf(fp, "AF:\n");
3748         fprintf(fp, "NF:0\n");
3749         fprintf(fp, "PS:10\n");
3750         fprintf(fp, "SRH:1\n");
3751         fprintf(fp, "SFN:\n");
3752         fprintf(fp, "DSR:\n");
3753         if (compose->msgid)
3754                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3755         else
3756                 fprintf(fp, "MID:\n");
3757         fprintf(fp, "CFG:\n");
3758         fprintf(fp, "PT:0\n");
3759         fprintf(fp, "S:%s\n", compose->account->address);
3760         fprintf(fp, "RQ:\n");
3761         if (mailac)
3762                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3763         else
3764                 fprintf(fp, "SSV:\n");
3765         if (newsac)
3766                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3767         else
3768                 fprintf(fp, "NSV:\n");
3769         fprintf(fp, "SSH:\n");
3770         /* write recepient list */
3771         if (compose->to_list) {
3772                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
3773                 for (cur = compose->to_list->next; cur != NULL;
3774                      cur = cur->next)
3775                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3776                 fprintf(fp, "\n");
3777         }
3778         /* write newsgroup list */
3779         if (compose->newsgroup_list) {
3780                 fprintf(fp, "NG:");
3781                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3782                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3783                         fprintf(fp, ",%s", (gchar *)cur->data);
3784                 fprintf(fp, "\n");
3785         }
3786         /* Sylpheed account IDs */
3787         if (mailac) {
3788                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3789         }
3790         if (newsac) {
3791                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3792         }
3793         /* Save copy folder */
3794         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3795                 gchar *savefolderid;
3796                 
3797                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3798                 fprintf(fp, "SCF:%s\n", savefolderid);
3799                 g_free(savefolderid);
3800         }
3801         /* Message-ID of message replying to */
3802         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
3803                 gchar *folderid;
3804                 
3805                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
3806                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
3807                 g_free(folderid);
3808         }
3809         /* Message-ID of message forwarding to */
3810         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
3811                 gchar *folderid;
3812                 
3813                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
3814                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
3815                 g_free(folderid);
3816         }
3817         fprintf(fp, "\n");
3818
3819         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3820                 if (fputs(buf, fp) == EOF) {
3821                         FILE_OP_ERROR(tmp, "fputs");
3822                         fclose(fp);
3823                         fclose(src_fp);
3824                         unlink(tmp);
3825                         g_free(tmp);
3826                         unlink(tmp2);
3827                         g_free(tmp2);
3828                         return -1;
3829                 }
3830         }
3831         fclose(src_fp);
3832         if (fclose(fp) == EOF) {
3833                 FILE_OP_ERROR(tmp, "fclose");
3834                 unlink(tmp);
3835                 g_free(tmp);
3836                 unlink(tmp2);
3837                 g_free(tmp2);
3838                 return -1;
3839         }
3840
3841         queue = account_get_special_folder(compose->account, F_QUEUE);
3842         if (!queue) {
3843                 g_warning("can't find queue folder\n");
3844                 unlink(tmp);
3845                 g_free(tmp);
3846                 return -1;
3847         }
3848         folder_item_scan(queue);
3849         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3850                 g_warning("can't queue the message\n");
3851                 unlink(tmp);
3852                 g_free(tmp);
3853                 return -1;
3854         }
3855         unlink(tmp);
3856         g_free(tmp);
3857         unlink(tmp2);
3858         g_free(tmp2);
3859
3860         if (compose->mode == COMPOSE_REEDIT) {
3861                 compose_remove_reedit_target(compose);
3862         }
3863
3864         if ((msgnum != NULL) && (item != NULL)) {
3865                 *msgnum = num;
3866                 *item = queue;
3867         }
3868
3869         return 0;
3870 }
3871
3872 static void compose_write_attach(Compose *compose, FILE *fp)
3873 {
3874         AttachInfo *ainfo;
3875         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3876         gint row;
3877         FILE *attach_fp;
3878         gchar filename[BUFFSIZE];
3879         gint len;
3880
3881         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3882              row++) {
3883                 if ((attach_fp = fopen(ainfo->file, "rb")) == NULL) {
3884                         g_warning("Can't open file %s\n", ainfo->file);
3885                         continue;
3886                 }
3887
3888                 fprintf(fp, "\n--%s\n", compose->boundary);
3889
3890                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3891                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3892                         fprintf(fp, "Content-Disposition: inline\n");
3893                 } else {
3894                         compose_convert_header(filename, sizeof(filename),
3895                                                ainfo->name, 12, FALSE);
3896                         fprintf(fp, "Content-Type: %s;\n"
3897                                     " name=\"%s\"\n",
3898                                 ainfo->content_type, filename);
3899                         fprintf(fp, "Content-Disposition: attachment;\n"
3900                                     " filename=\"%s\"\n", filename);
3901                 }
3902
3903                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3904                         procmime_get_encoding_str(ainfo->encoding));
3905
3906                 if (ainfo->encoding == ENC_BASE64) {
3907                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3908
3909                         while ((len = fread(inbuf, sizeof(gchar),
3910                                             B64_LINE_SIZE, attach_fp))
3911                                == B64_LINE_SIZE) {
3912                                 base64_encode(outbuf, inbuf, B64_LINE_SIZE);
3913                                 fputs(outbuf, fp);
3914                                 fputc('\n', fp);
3915                         }
3916                         if (len > 0 && feof(attach_fp)) {
3917                                 base64_encode(outbuf, inbuf, len);
3918                                 fputs(outbuf, fp);
3919                                 fputc('\n', fp);
3920                         }
3921                 } else if (ainfo->encoding == ENC_QUOTED_PRINTABLE) {
3922                         gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
3923
3924                         while (fgets(inbuf, sizeof(inbuf), attach_fp) != NULL) {
3925                                 qp_encode_line(outbuf, inbuf);
3926                                 fputs(outbuf, fp);
3927                         }
3928                 } else {
3929                         gchar buf[BUFFSIZE];
3930
3931                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3932                                 strcrchomp(buf);
3933                                 fputs(buf, fp);
3934                         }
3935                 }
3936
3937                 fclose(attach_fp);
3938         }
3939
3940         fprintf(fp, "\n--%s--\n", compose->boundary);
3941 }
3942
3943 #define QUOTE_IF_REQUIRED(out, str)                     \
3944 {                                                       \
3945         if (*str != '"' && strpbrk(str, ",.[]<>")) {    \
3946                 gchar *__tmp;                           \
3947                 gint len;                               \
3948                                                         \
3949                 len = strlen(str) + 3;                  \
3950                 Xalloca(__tmp, len, return -1);         \
3951                 g_snprintf(__tmp, len, "\"%s\"", str);  \
3952                 out = __tmp;                            \
3953         } else {                                        \
3954                 Xstrdup_a(out, str, return -1);         \
3955         }                                               \
3956 }
3957
3958 #define PUT_RECIPIENT_HEADER(header, str)                                    \
3959 {                                                                            \
3960         if (*str != '\0') {                                                  \
3961                 Xstrdup_a(str, str, return -1);                              \
3962                 g_strstrip(str);                                             \
3963                 if (*str != '\0') {                                          \
3964                         compose->to_list = address_list_append               \
3965                                 (compose->to_list, str);                     \
3966                         compose_convert_header                               \
3967                                 (buf, sizeof(buf), str, strlen(header) + 2,  \
3968                                  TRUE);                                      \
3969                         fprintf(fp, "%s: %s\n", header, buf);                \
3970                 }                                                            \
3971         }                                                                    \
3972 }
3973
3974 #define IS_IN_CUSTOM_HEADER(header) \
3975         (compose->account->add_customhdr && \
3976          custom_header_find(compose->account->customhdr_list, header) != NULL)
3977
3978 static gint compose_write_headers_from_headerlist(Compose *compose, 
3979                                                   FILE *fp, 
3980                                                   gchar *header)
3981 {
3982         gchar buf[BUFFSIZE];
3983         gchar *str, *header_w_colon, *trans_hdr;
3984         gboolean first_address;
3985         GSList *list;
3986         ComposeHeaderEntry *headerentry;
3987         gchar * headerentryname;
3988
3989         if (IS_IN_CUSTOM_HEADER(header)) {
3990                 return 0;
3991         }
3992
3993         debug_print("Writing %s-header\n", header);
3994
3995         header_w_colon = g_strconcat(header, ":", NULL);
3996         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3997
3998         first_address = TRUE;
3999         for (list = compose->header_list; list; list = list->next) {
4000                 headerentry = ((ComposeHeaderEntry *)list->data);
4001                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
4002
4003                 if (!g_strcasecmp(trans_hdr, headerentryname)) {
4004                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4005                         Xstrdup_a(str, str, return -1);
4006                         g_strstrip(str);
4007                         if (str[0] != '\0') {
4008                                 compose_convert_header
4009                                         (buf, sizeof(buf), str,
4010                                         strlen(header) + 2, TRUE);
4011                                 if (first_address) {
4012                                         fprintf(fp, "%s: ", header);
4013                                         first_address = FALSE;
4014                                 } else {
4015                                         fprintf(fp, ",");
4016                                 }
4017                                 fprintf(fp, "%s", buf);
4018                         }
4019                 }
4020         }
4021         if (!first_address) {
4022                 fprintf(fp, "\n");
4023         }
4024
4025         g_free(header_w_colon);
4026
4027         return(0);
4028 }
4029
4030 static gint compose_write_headers(Compose *compose, FILE *fp,
4031                                   const gchar *charset, EncodingType encoding,
4032                                   gboolean is_draft)
4033 {
4034         gchar buf[BUFFSIZE];
4035         gchar *str;
4036         gchar *name;
4037         GSList *list;
4038         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4039
4040         /* struct utsname utsbuf; */
4041
4042         g_return_val_if_fail(fp != NULL, -1);
4043         g_return_val_if_fail(charset != NULL, -1);
4044         g_return_val_if_fail(compose->account != NULL, -1);
4045         g_return_val_if_fail(compose->account->address != NULL, -1);
4046
4047         /* Save draft infos */
4048         if (is_draft) {
4049                 fprintf(fp, "X-Sylpheed-Account-Id:%d\n", compose->account->account_id);
4050                 fprintf(fp, "S:%s\n", compose->account->address);
4051                 if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
4052                         gchar *savefolderid;
4053
4054                         savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
4055                         fprintf(fp, "SCF:%s\n", savefolderid);
4056                         g_free(savefolderid);
4057                 }
4058                 fprintf(fp, "\n");
4059         }
4060
4061         /* Date */
4062         if (compose->account->add_date) {
4063                 get_rfc822_date(buf, sizeof(buf));
4064                 fprintf(fp, "Date: %s\n", buf);
4065         }
4066
4067         /* From */
4068         if (!IS_IN_CUSTOM_HEADER("From")) {
4069                 if (compose->account->name && *compose->account->name) {
4070                         compose_convert_header
4071                                 (buf, sizeof(buf), compose->account->name,
4072                                  strlen("From: "), TRUE);
4073                         QUOTE_IF_REQUIRED(name, buf);
4074                         fprintf(fp, "From: %s <%s>\n",
4075                                 name, compose->account->address);
4076                 } else
4077                         fprintf(fp, "From: %s\n", compose->account->address);
4078         }
4079         
4080         /* To */
4081         compose_write_headers_from_headerlist(compose, fp, "To");
4082 #if 0 /* NEW COMPOSE GUI */
4083         if (compose->use_to) {
4084                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
4085                 PUT_RECIPIENT_HEADER("To", str);
4086         }
4087 #endif
4088
4089         /* Newsgroups */
4090         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
4091 #if 0 /* NEW COMPOSE GUI */
4092         if (compose->use_newsgroups) {
4093                 str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
4094                 if (*str != '\0') {
4095                         Xstrdup_a(str, str, return -1);
4096                         g_strstrip(str);
4097                         remove_space(str);
4098                         if (*str != '\0') {
4099                                 compose->newsgroup_list =
4100                                         newsgroup_list_append
4101                                                 (compose->newsgroup_list, str);
4102                                 compose_convert_header(buf, sizeof(buf), str,
4103                                                        strlen("Newsgroups: "),
4104                                                        TRUE);
4105                                 fprintf(fp, "Newsgroups: %s\n", buf);
4106                         }
4107                 }
4108         }
4109 #endif
4110         /* Cc */
4111         compose_write_headers_from_headerlist(compose, fp, "Cc");
4112 #if 0 /* NEW COMPOSE GUI */
4113         if (compose->use_cc) {
4114                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
4115                 PUT_RECIPIENT_HEADER("Cc", str);
4116         }
4117 #endif
4118         /* Bcc */
4119         compose_write_headers_from_headerlist(compose, fp, "Bcc");
4120 #if 0 /* NEW COMPOSE GUI */
4121         if (compose->use_bcc) {
4122                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
4123                 PUT_RECIPIENT_HEADER("Bcc", str);
4124         }
4125 #endif
4126
4127         /* Subject */
4128         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
4129         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
4130                 Xstrdup_a(str, str, return -1);
4131                 g_strstrip(str);
4132                 if (*str != '\0') {
4133                         compose_convert_header(buf, sizeof(buf), str,
4134                                                strlen("Subject: "), FALSE);
4135                         fprintf(fp, "Subject: %s\n", buf);
4136                 }
4137         }
4138
4139         /* Message-ID */
4140         if (compose->account->gen_msgid) {
4141                 compose_generate_msgid(compose, buf, sizeof(buf));
4142                 fprintf(fp, "Message-Id: <%s>\n", buf);
4143                 compose->msgid = g_strdup(buf);
4144         }
4145
4146         if (compose->remove_references == FALSE) {
4147                 /* In-Reply-To */
4148                 if (compose->inreplyto && compose->to_list)
4149                         fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
4150         
4151                 /* References */
4152                 if (compose->references)
4153                         fprintf(fp, "References: %s\n", compose->references);
4154         }
4155
4156         /* Followup-To */
4157         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
4158 #if 0 /* NEW COMPOSE GUI */
4159         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
4160                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
4161                 if (*str != '\0') {
4162                         Xstrdup_a(str, str, return -1);
4163                         g_strstrip(str);
4164                         remove_space(str);
4165                         if (*str != '\0') {
4166                                 compose_convert_header(buf, sizeof(buf), str,
4167                                                        strlen("Followup-To: "),
4168                                                        TRUE);
4169                                 fprintf(fp, "Followup-To: %s\n", buf);
4170                         }
4171                 }
4172         }
4173 #endif
4174         /* Reply-To */
4175         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
4176 #if 0 /* NEW COMPOSE GUI */
4177         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
4178                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
4179                 if (*str != '\0') {
4180                         Xstrdup_a(str, str, return -1);
4181                         g_strstrip(str);
4182                         if (*str != '\0') {
4183                                 compose_convert_header(buf, sizeof(buf), str,
4184                                                        strlen("Reply-To: "),
4185                                                        TRUE);
4186                                 fprintf(fp, "Reply-To: %s\n", buf);
4187                         }
4188                 }
4189         }
4190 #endif
4191         /* Organization */
4192         if (compose->account->organization &&
4193             !IS_IN_CUSTOM_HEADER("Organization")) {
4194                 compose_convert_header(buf, sizeof(buf),
4195                                        compose->account->organization,
4196                                        strlen("Organization: "), FALSE);
4197                 fprintf(fp, "Organization: %s\n", buf);
4198         }
4199
4200         /* Program version and system info */
4201         /* uname(&utsbuf); */
4202         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer") &&
4203             !compose->newsgroup_list) {
4204                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
4205                         prog_version,
4206                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4207                         TARGET_ALIAS);
4208                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4209         }
4210         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4211                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4212                         prog_version,
4213                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4214                         TARGET_ALIAS);
4215                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4216         }
4217
4218         /* custom headers */
4219         if (compose->account->add_customhdr) {
4220                 GSList *cur;
4221
4222                 for (cur = compose->account->customhdr_list; cur != NULL;
4223                      cur = cur->next) {
4224                         CustomHeader *chdr = (CustomHeader *)cur->data;
4225
4226                         if (strcasecmp(chdr->name, "Date")         != 0 &&
4227                             strcasecmp(chdr->name, "From")         != 0 &&
4228                             strcasecmp(chdr->name, "To")           != 0 &&
4229                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
4230                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
4231                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
4232                             strcasecmp(chdr->name, "References")   != 0 &&
4233                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
4234                             strcasecmp(chdr->name, "Content-Type") != 0 &&
4235                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
4236                             != 0) {
4237                                 compose_convert_header
4238                                         (buf, sizeof(buf),
4239                                          chdr->value ? chdr->value : "",
4240                                          strlen(chdr->name) + 2, FALSE);
4241                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
4242                         }
4243                 }
4244         }
4245
4246         /* MIME */
4247         fprintf(fp, "Mime-Version: 1.0\n");
4248         if (compose_use_attach(compose)) {
4249                 get_rfc822_date(buf, sizeof(buf));
4250                 subst_char(buf, ' ', '_');
4251                 subst_char(buf, ',', '_');
4252                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
4253                                                     buf, (guint)compose);
4254                 fprintf(fp,
4255                         "Content-Type: multipart/mixed;\n"
4256                         " boundary=\"%s\"\n", compose->boundary);
4257         } else {
4258                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
4259                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
4260                         procmime_get_encoding_str(encoding));
4261         }
4262
4263         /* PRIORITY */
4264         switch (compose->priority) {
4265                 case PRIORITY_HIGHEST: fprintf(fp, "Importance: high\n"
4266                                                    "X-Priority: 1 (Highest)\n");
4267                         break;
4268                 case PRIORITY_HIGH: fprintf(fp, "Importance: high\n"
4269                                                 "X-Priority: 2 (High)\n");
4270                         break;
4271                 case PRIORITY_NORMAL: break;
4272                 case PRIORITY_LOW: fprintf(fp, "Importance: low\n"
4273                                                "X-Priority: 4 (Low)\n");
4274                         break;
4275                 case PRIORITY_LOWEST: fprintf(fp, "Importance: low\n"
4276                                                   "X-Priority: 5 (Lowest)\n");
4277                         break;
4278                 default: debug_print("compose: priority unknown : %d\n",
4279                                      compose->priority);
4280         }
4281
4282         /* Request Return Receipt */
4283         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4284                 if (compose->return_receipt) {
4285                         if (compose->account->name
4286                             && *compose->account->name) {
4287                                 compose_convert_header(buf, sizeof(buf), 
4288                                                        compose->account->name, 
4289                                                        strlen("Disposition-Notification-To: "),
4290                                                        TRUE);
4291                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4292                         } else
4293                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
4294                 }
4295         }
4296
4297         /* get special headers */
4298         for (list = compose->header_list; list; list = list->next) {
4299                 ComposeHeaderEntry *headerentry;
4300                 gchar *tmp;
4301                 gchar *headername;
4302                 gchar *headername_wcolon;
4303                 gchar *headername_trans;
4304                 gchar *headervalue;
4305                 gchar **string;
4306                 gboolean standard_header = FALSE;
4307
4308                 headerentry = ((ComposeHeaderEntry *)list->data);
4309                 
4310                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4311                 if (!strstr(tmp, ":")) {
4312                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4313                         headername = g_strdup(tmp);
4314                 } else {
4315                         headername_wcolon = g_strdup(tmp);
4316                         headername = g_strdup(strtok(tmp, ":"));
4317                 }
4318                 g_free(tmp);
4319                 
4320                 headervalue = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4321                 string = std_headers;
4322                 while (*string != NULL) {
4323                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4324                         if (!strcmp(headername_trans,headername_wcolon))
4325                                 standard_header = TRUE;
4326                         string++;
4327                 }
4328                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4329                         fprintf(fp, "%s %s\n", headername_wcolon, headervalue);
4330                                 
4331                 g_free(headername);
4332                 g_free(headername_wcolon);
4333                 
4334         }
4335
4336         /* separator between header and body */
4337         fputs("\n", fp);
4338
4339         return 0;
4340 }
4341
4342 #undef IS_IN_CUSTOM_HEADER
4343
4344 static void compose_convert_header(gchar *dest, gint len, gchar *src,
4345                                    gint header_len, gboolean addr_field)
4346 {
4347         g_return_if_fail(src != NULL);
4348         g_return_if_fail(dest != NULL);
4349
4350         if (len < 1) return;
4351
4352         g_strchomp(src);
4353
4354         conv_encode_header(dest, len, src, header_len, addr_field);
4355 }
4356
4357 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
4358 {
4359         struct tm *lt;
4360         time_t t;
4361         gchar *addr;
4362
4363         t = time(NULL);
4364         lt = localtime(&t);
4365
4366         if (compose->account && compose->account->address &&
4367             *compose->account->address) {
4368                 if (strchr(compose->account->address, '@'))
4369                         addr = g_strdup(compose->account->address);
4370                 else
4371                         addr = g_strconcat(compose->account->address, "@",
4372                                            get_domain_name(), NULL);
4373         } else
4374                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
4375                                    NULL);
4376
4377         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
4378                    lt->tm_year + 1900, lt->tm_mon + 1,
4379                    lt->tm_mday, lt->tm_hour,
4380                    lt->tm_min, lt->tm_sec,
4381                    (guint)random(), addr);
4382
4383         debug_print("generated Message-ID: %s\n", buf);
4384
4385         g_free(addr);
4386 }
4387
4388 static void compose_create_header_entry(Compose *compose) 
4389 {
4390         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4391
4392         GtkWidget *combo;
4393         GtkWidget *entry;
4394         GList *combo_list = NULL;
4395         gchar **string, *header = NULL;
4396         ComposeHeaderEntry *headerentry;
4397         gboolean standard_header = FALSE;
4398
4399         headerentry = g_new0(ComposeHeaderEntry, 1);
4400
4401         /* Combo box */
4402         combo = gtk_combo_new();
4403         string = headers; 
4404         while(*string != NULL) {
4405                 combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
4406                 string++;
4407         }
4408         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
4409         g_list_free(combo_list);
4410         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
4411         gtk_widget_show(combo);
4412         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
4413         if (compose->header_last) {     
4414                 gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4415                 string = headers;
4416                 while (*string != NULL) {
4417                         if (!strcmp(*string, last_header_entry))
4418                                 standard_header = TRUE;
4419                         string++;
4420                 }
4421                 if (standard_header)
4422                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4423         }
4424         if (!compose->header_last || !standard_header) {
4425                 switch(compose->account->protocol) {
4426                         case A_NNTP:
4427                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
4428                                 break;
4429                         default:
4430                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
4431                                 break;
4432                 }                                                                   
4433         }
4434         if (header)
4435                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
4436
4437         /* Entry field */
4438         entry = gtk_entry_new(); 
4439         gtk_widget_show(entry);
4440         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);
4441
4442         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
4443         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
4444         gtk_signal_connect(GTK_OBJECT(entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4445
4446         address_completion_register_entry(GTK_ENTRY(entry));
4447
4448         headerentry->compose = compose;
4449         headerentry->combo = combo;
4450         headerentry->entry = entry;
4451         headerentry->headernum = compose->header_nextrow;
4452
4453         compose->header_nextrow++;
4454         compose->header_last = headerentry;
4455 }
4456
4457 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
4458 {
4459         ComposeHeaderEntry *last_header;
4460         
4461         last_header = compose->header_last;
4462         
4463         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
4464         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
4465 }
4466
4467 static GtkWidget *compose_create_header(Compose *compose) 
4468 {
4469         GtkWidget *label;
4470         GtkWidget *hbox;
4471         GtkWidget *from_optmenu_hbox;
4472 #if 0 /* NEW COMPOSE GUI */
4473         GtkWidget *to_entry;
4474         GtkWidget *to_hbox;
4475         GtkWidget *newsgroups_entry;
4476         GtkWidget *newsgroups_hbox;
4477 #endif
4478         GtkWidget *header_scrolledwin;
4479         GtkWidget *header_table;
4480 #if 0 /* NEW COMPOSE GUI */
4481         GtkWidget *cc_entry;
4482         GtkWidget *cc_hbox;
4483         GtkWidget *bcc_entry;
4484         GtkWidget *bcc_hbox;
4485         GtkWidget *reply_entry;
4486         GtkWidget *reply_hbox;
4487         GtkWidget *followup_entry;
4488         GtkWidget *followup_hbox;
4489 #endif
4490
4491         gint count = 0;
4492
4493         /* header labels and entries */
4494         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4495         gtk_widget_show(header_scrolledwin);
4496         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
4497
4498         header_table = gtk_table_new(2, 2, FALSE);
4499         gtk_widget_show(header_table);
4500         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
4501         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
4502         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
4503         count = 0;
4504
4505         /* option menu for selecting accounts */
4506         hbox = gtk_hbox_new(FALSE, 0);
4507         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
4508         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
4509         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
4510                          GTK_FILL, 0, 2, 0);
4511         from_optmenu_hbox = compose_account_option_menu_create(compose);
4512         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
4513                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
4514 #if 0 /* NEW COMPOSE GUI */
4515         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4516 #endif
4517         count++;
4518
4519         compose->header_table = header_table;
4520         compose->header_list = NULL;
4521         compose->header_nextrow = count;
4522
4523         compose_create_header_entry(compose);
4524
4525 #if 0 /* NEW COMPOSE GUI */
4526         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
4527                                 "To:", TRUE); 
4528         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4529         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
4530                                 &count, "Newsgroups:", FALSE);
4531         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
4532
4533         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
4534
4535         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
4536                                 "Cc:", TRUE);
4537         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
4538         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
4539                                 "Bcc:", TRUE);
4540         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
4541         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
4542                                 "Reply-To:", TRUE);
4543         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
4544         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
4545                                 "Followup-To:", FALSE);
4546         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
4547
4548         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
4549
4550         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
4551                            GTK_SIGNAL_FUNC(to_activated), compose);
4552         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
4553                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
4554         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
4555                            GTK_SIGNAL_FUNC(subject_activated), compose);
4556         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
4557                            GTK_SIGNAL_FUNC(cc_activated), compose);
4558         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
4559                            GTK_SIGNAL_FUNC(bcc_activated), compose);
4560         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
4561                            GTK_SIGNAL_FUNC(replyto_activated), compose);
4562         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
4563                            GTK_SIGNAL_FUNC(followupto_activated), compose);
4564
4565         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
4566                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4567         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
4568                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4569         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
4570                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4571         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
4572                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4573         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
4574                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4575         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
4576                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4577         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
4578                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4579 #endif
4580
4581         compose->table            = NULL;
4582 #if 0 /* NEW COMPOSE GUI */
4583         compose->table            = table;
4584         compose->to_hbox          = to_hbox;
4585         compose->to_entry         = to_entry;
4586         compose->newsgroups_hbox  = newsgroups_hbox;
4587         compose->newsgroups_entry = newsgroups_entry;
4588 #endif
4589 #if 0 /* NEW COMPOSE GUI */
4590         compose->cc_hbox          = cc_hbox;
4591         compose->cc_entry         = cc_entry;
4592         compose->bcc_hbox         = bcc_hbox;
4593         compose->bcc_entry        = bcc_entry;
4594         compose->reply_hbox       = reply_hbox;
4595         compose->reply_entry      = reply_entry;
4596         compose->followup_hbox    = followup_hbox;
4597         compose->followup_entry   = followup_entry;
4598 #endif
4599
4600         return header_scrolledwin ;
4601 }
4602
4603 GtkWidget *compose_create_attach(Compose *compose)
4604 {
4605         gchar *titles[N_ATTACH_COLS];
4606         gint i;
4607
4608         GtkWidget *attach_scrwin;
4609         GtkWidget *attach_clist;
4610
4611         titles[COL_MIMETYPE] = _("MIME type");
4612         titles[COL_SIZE]     = _("Size");
4613         titles[COL_NAME]     = _("Name");
4614
4615         /* attachment list */
4616         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
4617         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
4618                                        GTK_POLICY_AUTOMATIC,
4619                                        GTK_POLICY_ALWAYS);
4620         gtk_widget_set_usize(attach_scrwin, -1, 80);
4621
4622         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
4623         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
4624                                            GTK_JUSTIFY_RIGHT);
4625         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
4626         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
4627         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
4628                                      GTK_SELECTION_EXTENDED);
4629         for (i = 0; i < N_ATTACH_COLS; i++)
4630                 GTK_WIDGET_UNSET_FLAGS
4631                         (GTK_CLIST(attach_clist)->column[i].button,
4632                          GTK_CAN_FOCUS);
4633         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
4634
4635         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
4636                            GTK_SIGNAL_FUNC(attach_selected), compose);
4637         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
4638                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
4639         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
4640                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
4641
4642         /* drag and drop */
4643         gtk_drag_dest_set(attach_clist,
4644                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4645                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4646         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
4647                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
4648                            compose);
4649
4650         compose->attach_scrwin = attach_scrwin;
4651         compose->attach_clist  = attach_clist;
4652
4653         return attach_scrwin;
4654 }
4655
4656 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
4657 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
4658
4659 static GtkWidget *compose_create_others(Compose *compose)
4660 {
4661         GtkWidget *table;
4662         GtkWidget *savemsg_checkbtn;
4663         GtkWidget *savemsg_entry;
4664         GtkWidget *savemsg_select;
4665         
4666         guint rowcount = 0;
4667         gchar *folderidentifier;
4668
4669         /* Table for settings */
4670         table = gtk_table_new(3, 1, FALSE);
4671         gtk_widget_show(table);
4672         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
4673         rowcount = 0;
4674
4675         /* Save Message to folder */
4676         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
4677         gtk_widget_show(savemsg_checkbtn);
4678         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4679         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4680                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
4681         }
4682         gtk_signal_connect(GTK_OBJECT(savemsg_checkbtn), "toggled",
4683                             GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
4684
4685         savemsg_entry = gtk_entry_new();
4686         gtk_widget_show(savemsg_entry);
4687         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
4688         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
4689         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4690                 folderidentifier = folder_item_get_identifier(account_get_special_folder
4691                                   (compose->account, F_OUTBOX));
4692                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
4693                 g_free(folderidentifier);
4694         }
4695
4696         savemsg_select = gtk_button_new_with_label (_("Select ..."));
4697         gtk_widget_show (savemsg_select);
4698         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4699         gtk_signal_connect (GTK_OBJECT (savemsg_select), "clicked",
4700                             GTK_SIGNAL_FUNC (compose_savemsg_select_cb),
4701                             compose);
4702
4703         rowcount++;
4704
4705         compose->savemsg_checkbtn = savemsg_checkbtn;
4706         compose->savemsg_entry = savemsg_entry;
4707
4708         return table;   
4709 }
4710
4711 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
4712 {
4713         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
4714                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
4715 }
4716
4717 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
4718 {
4719         FolderItem *dest;
4720         gchar * path;
4721
4722         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
4723         if (!dest) return;
4724
4725         path = folder_item_get_identifier(dest);
4726
4727         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
4728         g_free(path);
4729 }
4730
4731 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
4732 {
4733         Compose   *compose;
4734         GtkWidget *window;
4735         GtkWidget *vbox;
4736         GtkWidget *menubar;
4737         GtkWidget *handlebox;
4738
4739         GtkWidget *notebook;
4740
4741         GtkWidget *vbox2;
4742
4743         GtkWidget *label;
4744         GtkWidget *subject_hbox;
4745         GtkWidget *subject_frame;
4746         GtkWidget *subject_entry;
4747         GtkWidget *subject;
4748         GtkWidget *paned;
4749
4750         GtkWidget *edit_vbox;
4751         GtkWidget *ruler_hbox;
4752         GtkWidget *ruler;
4753         GtkWidget *scrolledwin;
4754         GtkWidget *text;
4755
4756         UndoMain *undostruct;
4757
4758         gchar *titles[N_ATTACH_COLS];
4759         guint n_menu_entries;
4760         GtkStyle  *style, *new_style;
4761         GdkColormap *cmap;
4762         GdkColor color[1];
4763         gboolean success[1];
4764         GtkWidget *popupmenu;
4765         GtkItemFactory *popupfactory;
4766         GtkItemFactory *ifactory;
4767         GtkWidget *tmpl_menu;
4768         gint n_entries;
4769
4770 #if USE_ASPELL
4771         GtkAspell * gtkaspell = NULL;
4772 #endif
4773
4774         static GdkGeometry geometry;
4775
4776         g_return_val_if_fail(account != NULL, NULL);
4777
4778         debug_print("Creating compose window...\n");
4779         compose = g_new0(Compose, 1);
4780
4781         titles[COL_MIMETYPE] = _("MIME type");
4782         titles[COL_SIZE]     = _("Size");
4783         titles[COL_NAME]     = _("Name");
4784
4785         compose->account = account;
4786
4787         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4788         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
4789         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
4790         gtk_window_set_wmclass(GTK_WINDOW(window), "compose window", "Sylpheed");
4791
4792         if (!geometry.max_width) {
4793                 geometry.max_width = gdk_screen_width();
4794                 geometry.max_height = gdk_screen_height();
4795         }
4796         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
4797                                       &geometry, GDK_HINT_MAX_SIZE);
4798
4799         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4800                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
4801         gtk_signal_connect(GTK_OBJECT(window), "destroy",
4802                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
4803         MANAGE_WINDOW_SIGNALS_CONNECT(window);
4804         gtk_widget_realize(window);
4805
4806         gtkut_widget_set_composer_icon(window);
4807
4808         vbox = gtk_vbox_new(FALSE, 0);
4809         gtk_container_add(GTK_CONTAINER(window), vbox);
4810
4811         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
4812         menubar = menubar_create(window, compose_entries,
4813                                  n_menu_entries, "<Compose>", compose);
4814         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
4815
4816         handlebox = gtk_handle_box_new();
4817         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
4818
4819         compose->toolbar = toolbar_create(TOOLBAR_COMPOSE, handlebox,
4820                                           (gpointer)compose);
4821
4822         vbox2 = gtk_vbox_new(FALSE, 2);
4823         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
4824         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
4825         
4826         /* Notebook */
4827         notebook = gtk_notebook_new();
4828         gtk_widget_set_usize(notebook, -1, 130);
4829         gtk_widget_show(notebook);
4830
4831         /* header labels and entries */
4832         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
4833         /* attachment list */
4834         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
4835         /* Others Tab */
4836         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
4837
4838         /* Subject */
4839         subject_hbox = gtk_hbox_new(FALSE, 0);
4840         gtk_widget_show(subject_hbox);
4841
4842         subject_frame = gtk_frame_new(NULL);
4843         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_OUT);
4844         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, BORDER_WIDTH+1);
4845         gtk_widget_show(subject_frame);
4846
4847         subject = gtk_hbox_new(FALSE, 0);
4848         gtk_container_set_border_width(GTK_CONTAINER(subject), BORDER_WIDTH);
4849         gtk_widget_show(subject);
4850
4851         label = gtk_label_new(_("Subject:"));
4852         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 4);
4853         gtk_widget_show(label);
4854
4855         subject_entry = gtk_entry_new();
4856         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 2);
4857         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4858         gtk_widget_show(subject_entry);
4859         compose->subject_entry = subject_entry;
4860         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
4861         
4862         edit_vbox = gtk_vbox_new(FALSE, 0);
4863 #if 0 /* NEW COMPOSE GUI */
4864         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
4865 #endif
4866
4867         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
4868
4869         /* ruler */
4870         ruler_hbox = gtk_hbox_new(FALSE, 0);
4871         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
4872
4873         ruler = gtk_shruler_new();
4874         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
4875         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
4876                            BORDER_WIDTH + 1);
4877         gtk_widget_set_usize(ruler_hbox, 1, -1);
4878
4879         /* text widget */
4880         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4881         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
4882                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
4883         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
4884         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
4885
4886         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
4887                             (GTK_SCROLLED_WINDOW(scrolledwin)),
4888                             gtk_scrolled_window_get_vadjustment
4889                             (GTK_SCROLLED_WINDOW(scrolledwin)));
4890         GTK_STEXT(text)->default_tab_width = 8;
4891         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
4892
4893         if (prefs_common.block_cursor) {
4894                 GTK_STEXT(text)->cursor_type = GTK_STEXT_CURSOR_BLOCK;
4895         }
4896         
4897         if (prefs_common.smart_wrapping) {      
4898                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
4899                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
4900         }               
4901
4902         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
4903
4904         gtk_signal_connect(GTK_OBJECT(text), "changed",
4905                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
4906         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
4907                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4908         gtk_signal_connect(GTK_OBJECT(text), "activate",
4909                            GTK_SIGNAL_FUNC(text_activated), compose);
4910         gtk_signal_connect(GTK_OBJECT(text), "insert_text",
4911                            GTK_SIGNAL_FUNC(text_inserted), compose);
4912         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
4913                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
4914                                  edit_vbox);
4915 #if 0
4916         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
4917                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
4918                                  compose);
4919 #endif
4920         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
4921                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
4922                                  ruler);
4923
4924         /* drag and drop */
4925         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4926                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4927         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
4928                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
4929                            compose);
4930         gtk_widget_show_all(vbox);
4931
4932         /* pane between attach clist and text */
4933         paned = gtk_vpaned_new();
4934         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
4935         gtk_paned_set_handle_size(GTK_PANED(paned), 12);
4936         gtk_container_add(GTK_CONTAINER(vbox2), paned);
4937         gtk_paned_add1(GTK_PANED(paned), notebook);
4938         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
4939         gtk_widget_show_all(paned);
4940
4941         style = gtk_widget_get_style(text);
4942
4943         /* workaround for the slow down of GtkSText when using Pixmap theme */
4944         if (style->engine) {
4945                 GtkThemeEngine *engine;
4946
4947                 engine = style->engine;
4948                 style->engine = NULL;
4949                 new_style = gtk_style_copy(style);
4950                 style->engine = engine;
4951         } else
4952                 new_style = gtk_style_copy(style);
4953
4954         if (prefs_common.textfont) {
4955                 GdkFont *font;
4956
4957                 if ((font = gtkut_font_load(prefs_common.textfont)) != NULL) {
4958                         gdk_font_unref(new_style->font);
4959                         new_style->font = font;
4960                 }
4961         }
4962
4963         gtk_widget_set_style(text, new_style);
4964
4965         color[0] = quote_color;
4966         cmap = gdk_window_get_colormap(window->window);
4967         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
4968         if (success[0] == FALSE) {
4969                 g_warning("Compose: color allocation failed.\n");
4970                 style = gtk_widget_get_style(text);
4971                 quote_color = style->black;
4972         }
4973
4974         n_entries = sizeof(compose_popup_entries) /
4975                 sizeof(compose_popup_entries[0]);
4976         popupmenu = menu_create_items(compose_popup_entries, n_entries,
4977                                       "<Compose>", &popupfactory,
4978                                       compose);
4979
4980         ifactory = gtk_item_factory_from_widget(menubar);
4981         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
4982         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
4983         menu_set_sensitive(ifactory, "/Message/Remove references", FALSE);
4984
4985         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
4986 #if 0 /* NEW COMPOSE GUI */
4987         gtk_widget_hide(bcc_hbox);
4988         gtk_widget_hide(bcc_entry);
4989         gtk_widget_hide(reply_hbox);
4990         gtk_widget_hide(reply_entry);
4991         gtk_widget_hide(followup_hbox);
4992         gtk_widget_hide(followup_entry);
4993         gtk_widget_hide(ruler_hbox);
4994         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4995         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4996         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4997
4998         if (account->protocol == A_NNTP) {
4999                 gtk_widget_hide(to_hbox);
5000                 gtk_widget_hide(to_entry);
5001                 gtk_widget_hide(cc_hbox);
5002                 gtk_widget_hide(cc_entry);
5003                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
5004                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
5005         } else {
5006                 gtk_widget_hide(newsgroups_hbox);
5007                 gtk_widget_hide(newsgroups_entry);
5008                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
5009         }
5010 #endif
5011
5012         action_update_compose_menu(ifactory, compose);
5013
5014
5015         undostruct = undo_init(text);
5016         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
5017                                    menubar);
5018
5019         address_completion_start(window);
5020
5021         compose->window        = window;
5022         compose->vbox          = vbox;
5023         compose->menubar       = menubar;
5024         compose->handlebox     = handlebox;
5025
5026         compose->vbox2         = vbox2;
5027
5028         compose->paned = paned;
5029
5030         compose->edit_vbox     = edit_vbox;
5031         compose->ruler_hbox    = ruler_hbox;
5032         compose->ruler         = ruler;
5033         compose->scrolledwin   = scrolledwin;
5034         compose->text          = text;
5035
5036         compose->focused_editable = NULL;
5037
5038         compose->popupmenu    = popupmenu;
5039         compose->popupfactory = popupfactory;
5040
5041         compose->tmpl_menu = tmpl_menu;
5042
5043         compose->mode = mode;
5044
5045         compose->targetinfo = NULL;
5046         compose->replyinfo  = NULL;
5047         compose->fwdinfo    = NULL;
5048
5049         compose->replyto     = NULL;
5050         compose->cc          = NULL;
5051         compose->bcc         = NULL;
5052         compose->followup_to = NULL;
5053
5054         compose->ml_post     = NULL;
5055
5056         compose->inreplyto   = NULL;
5057         compose->references  = NULL;
5058         compose->msgid       = NULL;
5059         compose->boundary    = NULL;
5060
5061 #if USE_GPGME
5062         compose->use_signing    = FALSE;
5063         compose->use_encryption = FALSE;
5064 #endif /* USE_GPGME */
5065
5066         compose->modified = FALSE;
5067
5068         compose->return_receipt = FALSE;
5069
5070         compose->to_list        = NULL;
5071         compose->newsgroup_list = NULL;
5072
5073         compose->undostruct = undostruct;
5074
5075         compose->sig_str = NULL;
5076
5077         compose->exteditor_file    = NULL;
5078         compose->exteditor_pid     = -1;
5079         compose->exteditor_readdes = -1;
5080         compose->exteditor_tag     = -1;
5081
5082 #if USE_ASPELL
5083         menu_set_sensitive(ifactory, "/Spelling", FALSE);
5084         if (mode != COMPOSE_REDIRECT) {
5085                 if (prefs_common.enable_aspell && prefs_common.dictionary &&
5086                     strcmp(prefs_common.dictionary, _("None"))) {
5087                         gtkaspell = gtkaspell_new(prefs_common.aspell_path,
5088                                                   prefs_common.dictionary,
5089                                                   conv_get_current_charset_str(),
5090                                                   prefs_common.misspelled_col,
5091                                                   prefs_common.check_while_typing,
5092                                                   prefs_common.use_alternate,
5093                                                   GTK_STEXT(text));
5094                         if (!gtkaspell) {
5095                                 alertpanel_error(_("Spell checker could not "
5096                                                 "be started.\n%s"),
5097                                                 gtkaspell_checkers_strerror());
5098                                 gtkaspell_checkers_reset_error();
5099                         } else {
5100
5101                                 GtkWidget *menuitem;
5102
5103                                 if (!gtkaspell_set_sug_mode(gtkaspell,
5104                                                 prefs_common.aspell_sugmode)) {
5105                                         debug_print("Aspell: could not set "
5106                                                     "suggestion mode %s\n",
5107                                                     gtkaspell_checkers_strerror());
5108                                         gtkaspell_checkers_reset_error();
5109                                 }
5110
5111                                 menuitem = gtk_item_factory_get_item(ifactory,
5112                                         "/Spelling/Spelling Configuration");
5113                                 gtkaspell_populate_submenu(gtkaspell, menuitem);
5114                                 menu_set_sensitive(ifactory, "/Spelling", TRUE);
5115                                 }
5116                 }
5117         }
5118 #endif
5119
5120         compose_select_account(compose, account, TRUE);
5121
5122 #if USE_ASPELL
5123         compose->gtkaspell      = gtkaspell;
5124 #endif
5125
5126         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
5127                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
5128
5129         if (account->set_autobcc) 
5130                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
5131         
5132         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
5133                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
5134
5135
5136         if (account->protocol != A_NNTP)
5137                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
5138         else
5139                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
5140
5141         addressbook_set_target_compose(compose);
5142         action_update_compose_menu(ifactory, compose);
5143         
5144         if (mode != COMPOSE_REDIRECT)
5145                 compose_set_template_menu(compose);
5146         else {
5147                 GtkWidget *menuitem;
5148                 menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5149                 menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
5150         }
5151
5152         compose_list = g_list_append(compose_list, compose);
5153
5154         if (!prefs_common.show_ruler)
5155                 gtk_widget_hide(ruler_hbox);
5156
5157         /* Priority */
5158         compose->priority = PRIORITY_NORMAL;
5159         compose_update_priority_menu_item(compose);
5160         
5161 #if USE_GPGME
5162         activate_gnupg_mode(compose, account);
5163 #endif  
5164         toolbar_set_style(compose->toolbar->toolbar, compose->handlebox, prefs_common.toolbar_style);
5165         gtk_widget_show(window);
5166         
5167         return compose;
5168 }
5169
5170 static GtkWidget *compose_account_option_menu_create(Compose *compose)
5171 {
5172         GList *accounts;
5173         GtkWidget *hbox;
5174         GtkWidget *optmenu;
5175         GtkWidget *menu;
5176         gint num = 0, def_menu = 0;
5177
5178         accounts = account_get_list();
5179         g_return_val_if_fail(accounts != NULL, NULL);
5180
5181         hbox = gtk_hbox_new(FALSE, 0);
5182         optmenu = gtk_option_menu_new();
5183         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5184         menu = gtk_menu_new();
5185
5186         for (; accounts != NULL; accounts = accounts->next, num++) {
5187                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
5188                 GtkWidget *menuitem;
5189                 gchar *name;
5190
5191                 if (ac == compose->account) def_menu = num;
5192
5193                 if (ac->name)
5194                         name = g_strdup_printf("%s: %s <%s>",
5195                                                ac->account_name,
5196                                                ac->name, ac->address);
5197                 else
5198                         name = g_strdup_printf("%s: %s",
5199                                                ac->account_name, ac->address);
5200                 MENUITEM_ADD(menu, menuitem, name, ac->account_id);
5201                 g_free(name);
5202                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
5203                                    GTK_SIGNAL_FUNC(account_activated),
5204                                    compose);
5205         }
5206
5207         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
5208         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
5209
5210         return hbox;
5211 }
5212
5213 static void compose_set_priority_cb(gpointer data,
5214                                     guint action,
5215                                     GtkWidget *widget)
5216 {
5217         Compose *compose = (Compose *) data;
5218         compose->priority = action;
5219 }
5220
5221 static void compose_update_priority_menu_item(Compose * compose)
5222 {
5223         GtkItemFactory *ifactory;
5224         GtkWidget *menuitem = NULL;
5225
5226         ifactory = gtk_item_factory_from_widget(compose->menubar);
5227         
5228         switch (compose->priority) {
5229                 case PRIORITY_HIGHEST:
5230                         menuitem = gtk_item_factory_get_item
5231                                 (ifactory, "/Message/Priority/Highest");
5232                         break;
5233                 case PRIORITY_HIGH:
5234                         menuitem = gtk_item_factory_get_item
5235                                 (ifactory, "/Message/Priority/High");
5236                         break;
5237                 case PRIORITY_NORMAL:
5238                         menuitem = gtk_item_factory_get_item
5239                                 (ifactory, "/Message/Priority/Normal");
5240                         break;
5241                 case PRIORITY_LOW:
5242                         menuitem = gtk_item_factory_get_item
5243                                 (ifactory, "/Message/Priority/Low");
5244                         break;
5245                 case PRIORITY_LOWEST:
5246                         menuitem = gtk_item_factory_get_item
5247                                 (ifactory, "/Message/Priority/Lowest");
5248                         break;
5249         }
5250         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5251 }       
5252
5253 #if USE_GPGME 
5254 static void compose_set_gnupg_mode_cb(gpointer data,
5255                                     guint action,
5256                                     GtkWidget *widget)
5257 {
5258         Compose *compose = (Compose *) data;
5259         compose->gnupg_mode = action;
5260 }
5261
5262 static void compose_update_gnupg_mode_menu_item(Compose * compose)
5263 {
5264         GtkItemFactory *ifactory;
5265         GtkWidget *menuitem = NULL;
5266
5267         ifactory = gtk_item_factory_from_widget(compose->menubar);
5268         
5269         switch (compose->gnupg_mode) {
5270                 case GNUPG_MODE_DETACH:
5271                         menuitem = gtk_item_factory_get_item
5272                                 (ifactory, "/Message/Mode/MIME");
5273                         break;
5274                 case GNUPG_MODE_INLINE:
5275                         menuitem = gtk_item_factory_get_item
5276                                 (ifactory, "/Message/Mode/Inline");
5277                         break;
5278         }
5279         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5280         
5281         if (compose->use_encryption == TRUE || compose->use_signing == TRUE)
5282                 menu_set_sensitive(ifactory, "/Message/Mode", TRUE);
5283         else 
5284                 menu_set_sensitive(ifactory, "/Message/Mode", FALSE);
5285 }       
5286 #endif
5287  
5288 static void compose_set_template_menu(Compose *compose)
5289 {
5290         GSList *tmpl_list, *cur;
5291         GtkWidget *menu;
5292         GtkWidget *item;
5293
5294         tmpl_list = template_get_config();
5295
5296         menu = gtk_menu_new();
5297
5298         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
5299                 Template *tmpl = (Template *)cur->data;
5300
5301                 item = gtk_menu_item_new_with_label(tmpl->name);
5302                 gtk_menu_append(GTK_MENU(menu), item);
5303                 gtk_signal_connect(GTK_OBJECT(item), "activate",
5304                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
5305                                    compose);
5306                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
5307                 gtk_widget_show(item);
5308         }
5309
5310         gtk_widget_show(menu);
5311         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
5312 }
5313
5314 void compose_reflect_prefs_all(void)
5315 {
5316         GList *cur;
5317         Compose *compose;
5318
5319         for (cur = compose_list; cur != NULL; cur = cur->next) {
5320                 compose = (Compose *)cur->data;
5321                 compose_set_template_menu(compose);
5322         }
5323 }
5324
5325 void compose_reflect_prefs_pixmap_theme(void)
5326 {
5327         GList *cur;
5328         Compose *compose;
5329
5330         for (cur = compose_list; cur != NULL; cur = cur->next) {
5331                 compose = (Compose *)cur->data;
5332                 toolbar_update(TOOLBAR_COMPOSE, compose);
5333         }
5334 }
5335
5336 static void compose_template_apply(Compose *compose, Template *tmpl,
5337                                    gboolean replace)
5338 {
5339         gchar *qmark;
5340         gchar *parsed_str;
5341
5342         if (!tmpl || !tmpl->value) return;
5343
5344         gtk_stext_freeze(GTK_STEXT(compose->text));
5345
5346         if (tmpl->subject && *tmpl->subject != '\0')
5347                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
5348                                    tmpl->subject);
5349         if (tmpl->to && *tmpl->to != '\0')
5350                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
5351         if (tmpl->cc && *tmpl->cc != '\0')
5352                 compose_entry_append(compose, tmpl->cc, COMPOSE_CC);
5353
5354         if (tmpl->bcc && *tmpl->bcc != '\0')
5355                 compose_entry_append(compose, tmpl->bcc, COMPOSE_BCC);
5356
5357         if (replace)
5358                 gtkut_stext_clear(GTK_STEXT(compose->text));
5359
5360         if ((compose->replyinfo == NULL) && (compose->fwdinfo == NULL)) {
5361                 parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
5362                                                NULL, NULL);
5363         } else {
5364                 if (prefs_common.quotemark && *prefs_common.quotemark)
5365                         qmark = prefs_common.quotemark;
5366                 else
5367                         qmark = "> ";
5368
5369                 if (compose->replyinfo != NULL)
5370                         parsed_str = compose_quote_fmt(compose, compose->replyinfo,
5371                                                        tmpl->value, qmark, NULL);
5372                 else if (compose->fwdinfo != NULL)
5373                         parsed_str = compose_quote_fmt(compose, compose->fwdinfo,
5374                                                        tmpl->value, qmark, NULL);
5375                 else
5376                         parsed_str = NULL;
5377         }
5378
5379         if (replace && parsed_str && compose->account->auto_sig)
5380                 compose_insert_sig(compose, FALSE);
5381
5382         if (replace && parsed_str) {
5383                 gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
5384                 gtk_stext_set_point(GTK_STEXT(compose->text), 0);
5385         }
5386
5387         if (parsed_str)
5388                 compose_changed_cb(NULL, compose);
5389
5390         gtk_stext_thaw(GTK_STEXT(compose->text));
5391 }
5392
5393 static void compose_destroy(Compose *compose)
5394 {
5395         gint row;
5396         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5397         AttachInfo *ainfo;
5398
5399         /* NOTE: address_completion_end() does nothing with the window
5400          * however this may change. */
5401         address_completion_end(compose->window);
5402
5403         slist_free_strings(compose->to_list);
5404         g_slist_free(compose->to_list);
5405         slist_free_strings(compose->newsgroup_list);
5406         g_slist_free(compose->newsgroup_list);
5407         slist_free_strings(compose->header_list);
5408         g_slist_free(compose->header_list);
5409
5410         procmsg_msginfo_free(compose->targetinfo);
5411         procmsg_msginfo_free(compose->replyinfo);
5412         procmsg_msginfo_free(compose->fwdinfo);
5413
5414         g_free(compose->replyto);
5415         g_free(compose->cc);
5416         g_free(compose->bcc);
5417         g_free(compose->newsgroups);
5418         g_free(compose->followup_to);
5419
5420         g_free(compose->ml_post);
5421
5422         g_free(compose->inreplyto);
5423         g_free(compose->references);
5424         g_free(compose->msgid);
5425         g_free(compose->boundary);
5426
5427         if (compose->redirect_filename)
5428                 g_free(compose->redirect_filename);
5429         if (compose->undostruct)
5430                 undo_destroy(compose->undostruct);
5431
5432         g_free(compose->sig_str);
5433
5434         g_free(compose->exteditor_file);
5435
5436         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
5437              row++)
5438                 compose_attach_info_free(ainfo);
5439
5440         if (addressbook_get_target_compose() == compose)
5441                 addressbook_set_target_compose(NULL);
5442
5443 #if USE_ASPELL
5444         if (compose->gtkaspell) {
5445                 gtkaspell_delete(compose->gtkaspell);
5446         }
5447 #endif
5448
5449         prefs_common.compose_width = compose->scrolledwin->allocation.width;
5450         prefs_common.compose_height = compose->window->allocation.height;
5451
5452         gtk_widget_destroy(compose->paned);
5453
5454         toolbar_destroy(compose->toolbar);
5455         g_free(compose->toolbar);
5456         g_free(compose);
5457
5458         compose_list = g_list_remove(compose_list, compose);
5459 }
5460
5461 static void compose_attach_info_free(AttachInfo *ainfo)
5462 {
5463         g_free(ainfo->file);
5464         g_free(ainfo->content_type);
5465         g_free(ainfo->name);
5466         g_free(ainfo);
5467 }
5468
5469 static void compose_attach_remove_selected(Compose *compose)
5470 {
5471         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5472         AttachInfo *ainfo;
5473         gint row;
5474
5475         while (clist->selection != NULL) {
5476                 row = GPOINTER_TO_INT(clist->selection->data);
5477                 ainfo = gtk_clist_get_row_data(clist, row);
5478                 compose_attach_info_free(ainfo);
5479                 gtk_clist_remove(clist, row);
5480         }
5481 }
5482
5483 static struct _AttachProperty
5484 {
5485         GtkWidget *window;
5486         GtkWidget *mimetype_entry;
5487         GtkWidget *encoding_optmenu;
5488         GtkWidget *path_entry;
5489         GtkWidget *filename_entry;
5490         GtkWidget *ok_btn;
5491         GtkWidget *cancel_btn;
5492 } attach_prop;
5493
5494 static void compose_attach_property(Compose *compose)
5495 {
5496         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5497         AttachInfo *ainfo;
5498         gint row;
5499         GtkOptionMenu *optmenu;
5500         static gboolean cancelled;
5501
5502         if (!clist->selection) return;
5503         row = GPOINTER_TO_INT(clist->selection->data);
5504
5505         ainfo = gtk_clist_get_row_data(clist, row);
5506         if (!ainfo) return;
5507
5508         if (!attach_prop.window)
5509                 compose_attach_property_create(&cancelled);
5510         gtk_widget_grab_focus(attach_prop.ok_btn);
5511         gtk_widget_show(attach_prop.window);
5512         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
5513
5514         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
5515         if (ainfo->encoding == ENC_UNKNOWN)
5516                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
5517                                     GINT_TO_POINTER(ENC_BASE64));
5518         else
5519                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
5520                                     GINT_TO_POINTER(ainfo->encoding));
5521
5522         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
5523                            ainfo->content_type ? ainfo->content_type : "");
5524         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
5525                            ainfo->file ? ainfo->file : "");
5526         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
5527                            ainfo->name ? ainfo->name : "");
5528
5529         for (;;) {
5530                 gchar *text;
5531                 gchar *cnttype = NULL;
5532                 gchar *file = NULL;
5533                 off_t size = 0;
5534                 GtkWidget *menu;
5535                 GtkWidget *menuitem;
5536
5537                 cancelled = FALSE;
5538                 gtk_main();
5539
5540                 if (cancelled == TRUE) {
5541                         gtk_widget_hide(attach_prop.window);
5542                         break;
5543                 }
5544
5545                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
5546                 if (*text != '\0') {
5547                         gchar *p;
5548
5549                         text = g_strstrip(g_strdup(text));
5550                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
5551                                 cnttype = g_strdup(text);
5552                                 g_free(text);
5553                         } else {
5554                                 alertpanel_error(_("Invalid MIME type."));
5555                                 g_free(text);
5556                                 continue;
5557                         }
5558                 }
5559
5560                 menu = gtk_option_menu_get_menu(optmenu);
5561                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
5562                 ainfo->encoding = GPOINTER_TO_INT
5563                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
5564
5565                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
5566                 if (*text != '\0') {
5567                         if (is_file_exist(text) &&
5568                             (size = get_file_size(text)) > 0)
5569                                 file = g_strdup(text);
5570                         else {
5571                                 alertpanel_error
5572                                         (_("File doesn't exist or is empty."));
5573                                 g_free(cnttype);
5574                                 continue;
5575                         }
5576                 }
5577
5578                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
5579                 if (*text != '\0') {
5580                         g_free(ainfo->name);
5581                         ainfo->name = g_strdup(text);
5582                 }
5583
5584                 if (cnttype) {
5585                         g_free(ainfo->content_type);
5586                         ainfo->content_type = cnttype;
5587                 }
5588                 if (file) {
5589                         g_free(ainfo->file);
5590                         ainfo->file = file;
5591                 }
5592                 if (size)
5593                         ainfo->size = size;
5594
5595                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
5596                                    ainfo->content_type);
5597                 gtk_clist_set_text(clist, row, COL_SIZE,
5598                                    to_human_readable(ainfo->size));
5599                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
5600
5601                 gtk_widget_hide(attach_prop.window);
5602                 break;
5603         }
5604 }
5605
5606 #define SET_LABEL_AND_ENTRY(str, entry, top) \
5607 { \
5608         label = gtk_label_new(str); \
5609         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
5610                          GTK_FILL, 0, 0, 0); \
5611         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
5612  \
5613         entry = gtk_entry_new(); \
5614         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
5615                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
5616 }
5617
5618 static void compose_attach_property_create(gboolean *cancelled)
5619 {
5620         GtkWidget *window;
5621         GtkWidget *vbox;
5622         GtkWidget *table;
5623         GtkWidget *label;
5624         GtkWidget *mimetype_entry;
5625         GtkWidget *hbox;
5626         GtkWidget *optmenu;
5627         GtkWidget *optmenu_menu;
5628         GtkWidget *menuitem;
5629         GtkWidget *path_entry;
5630         GtkWidget *filename_entry;
5631         GtkWidget *hbbox;
5632         GtkWidget *ok_btn;
5633         GtkWidget *cancel_btn;
5634         GList     *mime_type_list, *strlist;
5635
5636         debug_print("Creating attach_property window...\n");
5637
5638         window = gtk_window_new(GTK_WINDOW_DIALOG);
5639         gtk_widget_set_usize(window, 480, -1);
5640         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
5641         gtk_window_set_title(GTK_WINDOW(window), _("Properties"));
5642         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
5643         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
5644         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
5645                            GTK_SIGNAL_FUNC(attach_property_delete_event),
5646                            cancelled);
5647         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
5648                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
5649                            cancelled);
5650
5651         vbox = gtk_vbox_new(FALSE, 8);
5652         gtk_container_add(GTK_CONTAINER(window), vbox);
5653
5654         table = gtk_table_new(4, 2, FALSE);
5655         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
5656         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
5657         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
5658
5659         label = gtk_label_new(_("MIME type")); 
5660         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
5661                          GTK_FILL, 0, 0, 0); 
5662         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
5663         mimetype_entry = gtk_combo_new(); 
5664         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
5665                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5666                          
5667         /* stuff with list */
5668         mime_type_list = procmime_get_mime_type_list();
5669         strlist = NULL;
5670         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
5671                 MimeType *type = (MimeType *) mime_type_list->data;
5672                 strlist = g_list_append(strlist, 
5673                                 g_strdup_printf("%s/%s",
5674                                         type->type, type->sub_type));
5675         }
5676         
5677         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
5678
5679         for (mime_type_list = strlist; mime_type_list != NULL; 
5680                 mime_type_list = mime_type_list->next)
5681                 g_free(mime_type_list->data);
5682         g_list_free(strlist);
5683                          
5684         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
5685
5686         label = gtk_label_new(_("Encoding"));
5687         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
5688                          GTK_FILL, 0, 0, 0);
5689         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
5690
5691         hbox = gtk_hbox_new(FALSE, 0);
5692         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
5693                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5694
5695         optmenu = gtk_option_menu_new();
5696         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
5697
5698         optmenu_menu = gtk_menu_new();
5699         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
5700         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5701 #if 0
5702         gtk_widget_set_sensitive(menuitem, FALSE);
5703 #endif
5704         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
5705         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5706 #if 0
5707         gtk_widget_set_sensitive(menuitem, FALSE);
5708 #endif
5709         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable",
5710                      ENC_QUOTED_PRINTABLE);
5711         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5712
5713         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
5714
5715         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5716
5717         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
5718         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
5719
5720         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
5721                                 &cancel_btn, _("Cancel"), NULL, NULL);
5722         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
5723         gtk_widget_grab_default(ok_btn);
5724
5725         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
5726                            GTK_SIGNAL_FUNC(attach_property_ok),
5727                            cancelled);
5728         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
5729                            GTK_SIGNAL_FUNC(attach_property_cancel),
5730                            cancelled);
5731
5732         gtk_widget_show_all(vbox);
5733
5734         attach_prop.window           = window;
5735         attach_prop.mimetype_entry   = mimetype_entry;
5736         attach_prop.encoding_optmenu = optmenu;
5737         attach_prop.path_entry       = path_entry;
5738         attach_prop.filename_entry   = filename_entry;
5739         attach_prop.ok_btn           = ok_btn;
5740         attach_prop.cancel_btn       = cancel_btn;
5741 }
5742
5743 #undef SET_LABEL_AND_ENTRY
5744
5745 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
5746 {
5747         *cancelled = FALSE;
5748         gtk_main_quit();
5749 }
5750
5751 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
5752 {
5753         *cancelled = TRUE;
5754         gtk_main_quit();
5755 }
5756
5757 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
5758                                          gboolean *cancelled)
5759 {
5760         *cancelled = TRUE;
5761         gtk_main_quit();
5762
5763         return TRUE;
5764 }
5765
5766 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
5767                                         gboolean *cancelled)
5768 {
5769         if (event && event->keyval == GDK_Escape) {
5770                 *cancelled = TRUE;
5771                 gtk_main_quit();
5772         }
5773 }
5774
5775 static void compose_exec_ext_editor(Compose *compose)
5776 {
5777         gchar *tmp;
5778         pid_t pid;
5779         gint pipe_fds[2];
5780
5781         tmp = g_strdup_printf("%s%ctmpmsg.%08x", get_tmp_dir(),
5782                               G_DIR_SEPARATOR, (gint)compose);
5783
5784         if (pipe(pipe_fds) < 0) {
5785                 perror("pipe");
5786                 g_free(tmp);
5787                 return;
5788         }
5789
5790         if ((pid = fork()) < 0) {
5791                 perror("fork");
5792                 g_free(tmp);
5793                 return;
5794         }
5795
5796         if (pid != 0) {
5797                 /* close the write side of the pipe */
5798                 close(pipe_fds[1]);
5799
5800                 compose->exteditor_file    = g_strdup(tmp);
5801                 compose->exteditor_pid     = pid;
5802                 compose->exteditor_readdes = pipe_fds[0];
5803
5804                 compose_set_ext_editor_sensitive(compose, FALSE);
5805
5806                 compose->exteditor_tag =
5807                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
5808                                       compose_input_cb, compose);
5809         } else {        /* process-monitoring process */
5810                 pid_t pid_ed;
5811
5812                 if (setpgid(0, 0))
5813                         perror("setpgid");
5814
5815                 /* close the read side of the pipe */
5816                 close(pipe_fds[0]);
5817
5818                 if (compose_write_body_to_file(compose, tmp) < 0) {
5819                         fd_write_all(pipe_fds[1], "2\n", 2);
5820                         _exit(1);
5821                 }
5822
5823                 pid_ed = compose_exec_ext_editor_real(tmp);
5824                 if (pid_ed < 0) {
5825                         fd_write_all(pipe_fds[1], "1\n", 2);
5826                         _exit(1);
5827                 }
5828
5829                 /* wait until editor is terminated */
5830                 waitpid(pid_ed, NULL, 0);
5831
5832                 fd_write_all(pipe_fds[1], "0\n", 2);
5833
5834                 close(pipe_fds[1]);
5835                 _exit(0);
5836         }
5837
5838         g_free(tmp);
5839 }
5840
5841 static gint compose_exec_ext_editor_real(const gchar *file)
5842 {
5843         static gchar *def_cmd = "emacs %s";
5844         gchar buf[1024];
5845         gchar *p;
5846         gchar **cmdline;
5847         pid_t pid;
5848
5849         g_return_val_if_fail(file != NULL, -1);
5850
5851         if ((pid = fork()) < 0) {
5852                 perror("fork");
5853                 return -1;
5854         }
5855
5856         if (pid != 0) return pid;
5857
5858         /* grandchild process */
5859
5860         if (setpgid(0, getppid()))
5861                 perror("setpgid");
5862
5863         if (prefs_common.ext_editor_cmd &&
5864             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
5865             *(p + 1) == 's' && !strchr(p + 2, '%')) {
5866                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
5867         } else {
5868                 if (prefs_common.ext_editor_cmd)
5869                         g_warning("External editor command line is invalid: `%s'\n",
5870                                   prefs_common.ext_editor_cmd);
5871                 g_snprintf(buf, sizeof(buf), def_cmd, file);
5872         }
5873
5874         cmdline = strsplit_with_quote(buf, " ", 1024);
5875         execvp(cmdline[0], cmdline);
5876
5877         perror("execvp");
5878         g_strfreev(cmdline);
5879
5880         _exit(1);
5881 }
5882
5883 static gboolean compose_ext_editor_kill(Compose *compose)
5884 {
5885         pid_t pgid = compose->exteditor_pid * -1;
5886         gint ret;
5887
5888         ret = kill(pgid, 0);
5889
5890         if (ret == 0 || (ret == -1 && EPERM == errno)) {
5891                 AlertValue val;
5892                 gchar *msg;
5893
5894                 msg = g_strdup_printf
5895                         (_("The external editor is still working.\n"
5896                            "Force terminating the process?\n"
5897                            "process group id: %d"), -pgid);
5898                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
5899                 g_free(msg);
5900
5901                 if (val == G_ALERTDEFAULT) {
5902                         gdk_input_remove(compose->exteditor_tag);
5903                         close(compose->exteditor_readdes);
5904
5905                         if (kill(pgid, SIGTERM) < 0) perror("kill");
5906                         waitpid(compose->exteditor_pid, NULL, 0);
5907
5908                         g_warning("Terminated process group id: %d", -pgid);
5909                         g_warning("Temporary file: %s",
5910                                   compose->exteditor_file);
5911
5912                         compose_set_ext_editor_sensitive(compose, TRUE);
5913
5914                         g_free(compose->exteditor_file);
5915                         compose->exteditor_file    = NULL;
5916                         compose->exteditor_pid     = -1;
5917                         compose->exteditor_readdes = -1;
5918                         compose->exteditor_tag     = -1;
5919                 } else
5920                         return FALSE;
5921         }
5922
5923         return TRUE;
5924 }
5925
5926 static void compose_input_cb(gpointer data, gint source,
5927                              GdkInputCondition condition)
5928 {
5929         gchar buf[3];
5930         Compose *compose = (Compose *)data;
5931         gint i = 0;
5932
5933         debug_print("Compose: input from monitoring process\n");
5934
5935         gdk_input_remove(compose->exteditor_tag);
5936
5937         for (;;) {
5938                 if (read(source, &buf[i], 1) < 1) {
5939                         buf[0] = '3';
5940                         break;
5941                 }
5942                 if (buf[i] == '\n') {
5943                         buf[i] = '\0';
5944                         break;
5945                 }
5946                 i++;
5947                 if (i == sizeof(buf) - 1)
5948                         break;
5949         }
5950
5951         waitpid(compose->exteditor_pid, NULL, 0);
5952
5953         if (buf[0] == '0') {            /* success */
5954                 GtkSText *text = GTK_STEXT(compose->text);
5955
5956                 gtk_stext_freeze(text);
5957                 gtk_stext_set_point(text, 0);
5958                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5959                 compose_insert_file(compose, compose->exteditor_file);
5960                 compose_changed_cb(NULL, compose);
5961                 gtk_stext_thaw(text);
5962
5963                 if (unlink(compose->exteditor_file) < 0)
5964                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5965         } else if (buf[0] == '1') {     /* failed */
5966                 g_warning("Couldn't exec external editor\n");
5967                 if (unlink(compose->exteditor_file) < 0)
5968                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5969         } else if (buf[0] == '2') {
5970                 g_warning("Couldn't write to file\n");
5971         } else if (buf[0] == '3') {
5972                 g_warning("Pipe read failed\n");
5973         }
5974
5975         close(source);
5976
5977         compose_set_ext_editor_sensitive(compose, TRUE);
5978
5979         g_free(compose->exteditor_file);
5980         compose->exteditor_file    = NULL;
5981         compose->exteditor_pid     = -1;
5982         compose->exteditor_readdes = -1;
5983         compose->exteditor_tag     = -1;
5984 }
5985
5986 static void compose_set_ext_editor_sensitive(Compose *compose,
5987                                              gboolean sensitive)
5988 {
5989         GtkItemFactory *ifactory;
5990
5991         ifactory = gtk_item_factory_from_widget(compose->menubar);
5992
5993         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
5994         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
5995         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
5996                            sensitive);
5997         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
5998         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
5999         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
6000         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
6001         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
6002                            sensitive);
6003
6004         gtk_widget_set_sensitive(compose->text,                   sensitive);
6005         gtk_widget_set_sensitive(compose->toolbar->send_btn,      sensitive);
6006         gtk_widget_set_sensitive(compose->toolbar->sendl_btn,     sensitive);
6007         gtk_widget_set_sensitive(compose->toolbar->draft_btn,     sensitive);
6008         gtk_widget_set_sensitive(compose->toolbar->insert_btn,    sensitive);
6009         gtk_widget_set_sensitive(compose->toolbar->sig_btn,       sensitive);
6010         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, sensitive);
6011         gtk_widget_set_sensitive(compose->toolbar->linewrap_btn,  sensitive);
6012 }
6013
6014 /**
6015  * compose_undo_state_changed:
6016  *
6017  * Change the sensivity of the menuentries undo and redo
6018  **/
6019 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
6020                                        gint redo_state, gpointer data)
6021 {
6022         GtkWidget *widget = GTK_WIDGET(data);
6023         GtkItemFactory *ifactory;
6024
6025         g_return_if_fail(widget != NULL);
6026
6027         debug_print("Set_undo.  UNDO:%i  REDO:%i\n", undo_state, redo_state);
6028
6029         ifactory = gtk_item_factory_from_widget(widget);
6030
6031         switch (undo_state) {
6032         case UNDO_STATE_TRUE:
6033                 if (!undostruct->undo_state) {
6034                         debug_print ("Set_undo - Testpoint\n");
6035                         undostruct->undo_state = TRUE;
6036                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
6037                 }
6038                 break;
6039         case UNDO_STATE_FALSE:
6040                 if (undostruct->undo_state) {
6041                         undostruct->undo_state = FALSE;
6042                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
6043                 }
6044                 break;
6045         case UNDO_STATE_UNCHANGED:
6046                 break;
6047         case UNDO_STATE_REFRESH:
6048                 menu_set_sensitive(ifactory, "/Edit/Undo",
6049                                    undostruct->undo_state);
6050                 break;
6051         default:
6052                 g_warning("Undo state not recognized");
6053                 break;
6054         }
6055
6056         switch (redo_state) {
6057         case UNDO_STATE_TRUE:
6058                 if (!undostruct->redo_state) {
6059                         undostruct->redo_state = TRUE;
6060                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
6061                 }
6062                 break;
6063         case UNDO_STATE_FALSE:
6064                 if (undostruct->redo_state) {
6065                         undostruct->redo_state = FALSE;
6066                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
6067                 }
6068                 break;
6069         case UNDO_STATE_UNCHANGED:
6070                 break;
6071         case UNDO_STATE_REFRESH:
6072                 menu_set_sensitive(ifactory, "/Edit/Redo",
6073                                    undostruct->redo_state);
6074                 break;
6075         default:
6076                 g_warning("Redo state not recognized");
6077                 break;
6078         }
6079 }
6080
6081 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
6082 {
6083         gint cursor_pos;
6084
6085         cursor_pos = (text->cursor_pos_x - extra) / char_width;
6086         cursor_pos = MAX(cursor_pos, 0);
6087
6088         return cursor_pos;
6089 }
6090
6091 /* callback functions */
6092
6093 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
6094  * includes "non-client" (windows-izm) in calculation, so this calculation
6095  * may not be accurate.
6096  */
6097 static gboolean compose_edit_size_alloc(GtkEditable *widget,
6098                                         GtkAllocation *allocation,
6099                                         GtkSHRuler *shruler)
6100 {
6101         if (prefs_common.show_ruler) {
6102                 gint char_width;
6103                 gint line_width_in_chars;
6104
6105                 char_width = gtkut_get_font_width
6106                         (GTK_WIDGET(widget)->style->font);
6107                 line_width_in_chars =
6108                         (allocation->width - allocation->x) / char_width;
6109
6110                 /* got the maximum */
6111                 gtk_ruler_set_range(GTK_RULER(shruler),
6112                                     0.0, line_width_in_chars,
6113                                     calc_cursor_xpos(GTK_STEXT(widget),
6114                                                      allocation->x,
6115                                                      char_width),
6116                                     /*line_width_in_chars*/ char_width);
6117         }
6118
6119         return TRUE;
6120 }
6121
6122 static void account_activated(GtkMenuItem *menuitem, gpointer data)
6123 {
6124         Compose *compose = (Compose *)data;
6125
6126         PrefsAccount *ac;
6127
6128         ac = account_find_from_id(
6129                 GPOINTER_TO_INT(gtk_object_get_user_data(GTK_OBJECT(menuitem))));
6130         g_return_if_fail(ac != NULL);
6131
6132         if (ac != compose->account)
6133                 compose_select_account(compose, ac, FALSE);
6134 }
6135
6136 static void attach_selected(GtkCList *clist, gint row, gint column,
6137                             GdkEvent *event, gpointer data)
6138 {
6139         Compose *compose = (Compose *)data;
6140
6141         if (event && event->type == GDK_2BUTTON_PRESS)
6142                 compose_attach_property(compose);
6143 }
6144
6145 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
6146                                   gpointer data)
6147 {
6148         Compose *compose = (Compose *)data;
6149         GtkCList *clist = GTK_CLIST(compose->attach_clist);
6150         gint row, column;
6151
6152         if (!event) return;
6153
6154         if (event->button == 3) {
6155                 if ((clist->selection && !clist->selection->next) ||
6156                     !clist->selection) {
6157                         gtk_clist_unselect_all(clist);
6158                         if (gtk_clist_get_selection_info(clist,
6159                                                          event->x, event->y,
6160                                                          &row, &column)) {
6161                                 gtk_clist_select_row(clist, row, column);
6162                                 gtkut_clist_set_focus_row(clist, row);
6163                         }
6164                 }
6165                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
6166                                NULL, NULL, event->button, event->time);
6167         }
6168 }
6169
6170 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
6171                                gpointer data)
6172 {
6173         Compose *compose = (Compose *)data;
6174
6175         if (!event) return;
6176
6177         switch (event->keyval) {
6178         case GDK_Delete:
6179                 compose_attach_remove_selected(compose);
6180                 break;
6181         }
6182 }
6183
6184 static void compose_allow_user_actions (Compose *compose, gboolean allow)
6185 {
6186         GtkItemFactory *ifactory = gtk_item_factory_from_widget(compose->menubar);
6187         toolbar_comp_set_sensitive(compose, allow);
6188         menu_set_sensitive(ifactory, "/File", allow);
6189         menu_set_sensitive(ifactory, "/Edit", allow);
6190         menu_set_sensitive(ifactory, "/Spelling", allow);
6191         menu_set_sensitive(ifactory, "/Message", allow);
6192         menu_set_sensitive(ifactory, "/Tools", allow);
6193         menu_set_sensitive(ifactory, "/Help", allow);
6194 }
6195
6196 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
6197 {
6198         Compose *compose = (Compose *)data;
6199         gint val;
6200         
6201         if (prefs_common.work_offline)
6202                 if (alertpanel(_("Offline warning"), 
6203                                _("You're working offline. Override?"),
6204                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
6205                         return;
6206         
6207         compose_allow_user_actions (compose, FALSE);
6208         compose->sending = TRUE;
6209         val = compose_send(compose);
6210         compose_allow_user_actions (compose, TRUE);
6211         compose->sending = FALSE;
6212
6213         if (val == 0) gtk_widget_destroy(compose->window);
6214 }
6215
6216 static void compose_send_later_cb(gpointer data, guint action,
6217                                   GtkWidget *widget)
6218 {
6219         Compose *compose = (Compose *)data;
6220         gint val;
6221
6222         val = compose_queue_sub(compose, NULL, NULL, TRUE);
6223         if (!val) gtk_widget_destroy(compose->window);
6224 }
6225
6226 void compose_draft (gpointer data) 
6227 {
6228         compose_draft_cb(data, 0, NULL);        
6229 }
6230
6231 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
6232 {
6233         Compose *compose = (Compose *)data;
6234         FolderItem *draft;
6235         gchar *tmp;
6236         gint msgnum;
6237         static gboolean lock = FALSE;
6238         MsgInfo *newmsginfo;
6239         
6240         if (lock) return;
6241
6242         draft = account_get_special_folder(compose->account, F_DRAFT);
6243         g_return_if_fail(draft != NULL);
6244
6245         lock = TRUE;
6246
6247         tmp = g_strdup_printf("%s%cdraft.%08x", get_tmp_dir(),
6248                               G_DIR_SEPARATOR, (gint)compose);
6249
6250         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
6251                 g_free(tmp);
6252                 lock = FALSE;
6253                 return;
6254         }
6255
6256         if ((msgnum = folder_item_add_msg(draft, tmp, TRUE)) < 0) {
6257                 unlink(tmp);
6258                 g_free(tmp);
6259                 lock = FALSE;
6260                 return;
6261         }
6262         g_free(tmp);
6263         draft->mtime = 0;       /* force updating */
6264
6265         if (compose->mode == COMPOSE_REEDIT) {
6266                 compose_remove_reedit_target(compose);
6267         }
6268
6269         newmsginfo = folder_item_get_msginfo(draft, msgnum);
6270         if (newmsginfo) {
6271                 procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
6272                 procmsg_msginfo_set_flags(newmsginfo, 0, MSG_DRAFT);
6273                 procmsg_msginfo_free(newmsginfo);
6274         }
6275         
6276         lock = FALSE;
6277
6278         /* 0: quit editing  1: keep editing  2: keep editing (autosave) */
6279         if (action == 0)
6280                 gtk_widget_destroy(compose->window);
6281         else {
6282                 struct stat s;
6283                 gchar *path;
6284
6285                 path = folder_item_fetch_msg(draft, msgnum);
6286                 g_return_if_fail(path != NULL);
6287                 if (stat(path, &s) < 0) {
6288                         FILE_OP_ERROR(path, "stat");
6289                         g_free(path);
6290                         lock = FALSE;
6291                         return;
6292                 }
6293                 g_free(path);
6294
6295                 procmsg_msginfo_free(compose->targetinfo);
6296                 compose->targetinfo = procmsg_msginfo_new();
6297                 compose->targetinfo->msgnum = msgnum;
6298                 compose->targetinfo->size = s.st_size;
6299                 compose->targetinfo->mtime = s.st_mtime;
6300                 compose->targetinfo->folder = draft;
6301                 compose->mode = COMPOSE_REEDIT;
6302                 
6303                 if (action == 2) {
6304                         compose->autosaved_draft = compose->targetinfo;
6305                 }
6306         }
6307 }
6308
6309 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
6310 {
6311         Compose *compose = (Compose *)data;
6312         GList *file_list;
6313
6314         if (compose->redirect_filename != NULL)
6315                 return;
6316
6317         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6318
6319         if (file_list) {
6320                 GList *tmp;
6321
6322                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6323                         gchar *file = (gchar *) tmp->data;
6324                         compose_attach_append(compose, file, file, NULL);
6325                         compose_changed_cb(NULL, compose);
6326                         g_free(file);
6327                 }
6328                 g_list_free(file_list);
6329         }               
6330 }
6331
6332 static void compose_insert_file_cb(gpointer data, guint action,
6333                                    GtkWidget *widget)
6334 {
6335         Compose *compose = (Compose *)data;
6336         GList *file_list;
6337
6338         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6339
6340         if (file_list) {
6341                 GList *tmp;
6342
6343                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6344                         gchar *file = (gchar *) tmp->data;
6345                         compose_insert_file(compose, file);
6346                         g_free(file);
6347                 }
6348                 g_list_free(file_list);
6349         }
6350 }
6351
6352 static void compose_insert_sig_cb(gpointer data, guint action,
6353                                   GtkWidget *widget)
6354 {
6355         Compose *compose = (Compose *)data;
6356
6357         compose_insert_sig(compose, FALSE);
6358 }
6359
6360 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
6361                               gpointer data)
6362 {
6363         Compose *compose = (Compose *)data;
6364         if (compose->sending)
6365                 return TRUE;
6366         compose_close_cb(compose, 0, NULL);
6367         return TRUE;
6368 }
6369
6370 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
6371 {
6372         Compose *compose = (Compose *)data;
6373         AlertValue val;
6374         
6375         if (compose->exteditor_tag != -1) {
6376                 if (!compose_ext_editor_kill(compose))
6377                         return;
6378         }
6379
6380         if (compose->modified) {
6381                 val = alertpanel(_("Discard message"),
6382                                  _("This message has been modified. discard it?"),
6383                                  _("Discard"), _("to Draft"), _("Cancel"));
6384
6385                 switch (val) {
6386                 case G_ALERTDEFAULT:
6387                         if (prefs_common.autosave)
6388                                 compose_remove_draft(compose);                  
6389                         break;
6390                 case G_ALERTALTERNATE:
6391                         compose_draft_cb(data, 0, NULL);
6392                         return;
6393                 default:
6394                         return;
6395                 }
6396         }
6397
6398         gtk_widget_destroy(compose->window);
6399 }
6400
6401 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
6402 {
6403         Compose *compose = (Compose *)data;
6404
6405         addressbook_open(compose);
6406 }
6407
6408 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
6409 {
6410         Compose *compose = (Compose *)data;
6411         Template *tmpl;
6412         gchar *msg;
6413         AlertValue val;
6414
6415         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
6416         g_return_if_fail(tmpl != NULL);
6417
6418         msg = g_strdup_printf(_("Do you want to apply the template `%s' ?"),
6419                               tmpl->name);
6420         val = alertpanel(_("Apply template"), msg,
6421                          _("Replace"), _("Insert"), _("Cancel"));
6422         g_free(msg);
6423
6424         if (val == G_ALERTDEFAULT)
6425                 compose_template_apply(compose, tmpl, TRUE);
6426         else if (val == G_ALERTALTERNATE)
6427                 compose_template_apply(compose, tmpl, FALSE);
6428 }
6429
6430 static void compose_ext_editor_cb(gpointer data, guint action,
6431                                   GtkWidget *widget)
6432 {
6433         Compose *compose = (Compose *)data;
6434
6435         compose_exec_ext_editor(compose);
6436 }
6437
6438 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
6439 {
6440         if (compose->sending)
6441                 return;
6442         compose_destroy(compose);
6443 }
6444
6445 static void compose_undo_cb(Compose *compose)
6446 {
6447         undo_undo(compose->undostruct);
6448 }
6449
6450 static void compose_redo_cb(Compose *compose)
6451 {
6452         undo_redo(compose->undostruct);
6453 }
6454
6455 static void compose_cut_cb(Compose *compose)
6456 {
6457         if (compose->focused_editable &&
6458             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6459                 gtk_editable_cut_clipboard
6460                         (GTK_EDITABLE(compose->focused_editable));
6461 }
6462
6463 static void compose_copy_cb(Compose *compose)
6464 {
6465         if (compose->focused_editable &&
6466             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6467                 gtk_editable_copy_clipboard
6468                         (GTK_EDITABLE(compose->focused_editable));
6469 }
6470
6471 static void compose_paste_cb(Compose *compose)
6472 {
6473         if (compose->focused_editable &&
6474             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6475                 gtk_editable_paste_clipboard
6476                         (GTK_EDITABLE(compose->focused_editable));
6477 }
6478
6479 static void compose_paste_as_quote_cb(Compose *compose)
6480 {
6481         if (compose->focused_editable &&
6482             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
6483                 /* let text_insert() (called directly or at a later time
6484                  * after the gtk_editable_paste_clipboard) know that 
6485                  * text is to be inserted as a quotation. implemented
6486                  * by using a simple refcount... */
6487                 gint paste_as_quotation = GPOINTER_TO_INT(gtk_object_get_data(
6488                                                 GTK_OBJECT(compose->focused_editable),
6489                                                 "paste_as_quotation"));
6490                 gtk_object_set_data(GTK_OBJECT(compose->focused_editable),
6491                                     "paste_as_quotation",
6492                                     GINT_TO_POINTER(paste_as_quotation + 1));
6493                 gtk_editable_paste_clipboard
6494                         (GTK_EDITABLE(compose->focused_editable));
6495         }
6496 }
6497
6498 static void compose_allsel_cb(Compose *compose)
6499 {
6500         if (compose->focused_editable &&
6501             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6502                 gtk_editable_select_region
6503                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
6504 }
6505
6506 static void compose_gtk_stext_action_cb(Compose *compose,
6507                                         ComposeCallGtkSTextAction action)
6508 {
6509         GtkSText *text = GTK_STEXT(compose->text);
6510         static struct {
6511                 void (*do_action) (GtkSText *text);
6512         } action_table[] = {
6513                 {gtk_stext_move_beginning_of_line},
6514                 {gtk_stext_move_forward_character},
6515                 {gtk_stext_move_backward_character},
6516                 {gtk_stext_move_forward_word},
6517                 {gtk_stext_move_backward_word},
6518                 {gtk_stext_move_end_of_line},
6519                 {gtk_stext_move_next_line},
6520                 {gtk_stext_move_previous_line},
6521                 {gtk_stext_delete_forward_character},
6522                 {gtk_stext_delete_backward_character},
6523                 {gtk_stext_delete_forward_word},
6524                 {gtk_stext_delete_backward_word},
6525                 {gtk_stext_delete_line},
6526                 {gtk_stext_delete_line}, /* gtk_stext_delete_line_n */
6527                 {gtk_stext_delete_to_line_end}
6528         };
6529
6530         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
6531
6532         if (action >= COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE &&
6533             action <= COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END)
6534                 action_table[action].do_action(text);
6535 }
6536
6537 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
6538 {
6539         if (GTK_IS_EDITABLE(widget))
6540                 compose->focused_editable = widget;
6541 }
6542
6543 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
6544 {
6545         if (compose->modified == FALSE) {
6546                 compose->modified = TRUE;
6547                 compose_set_title(compose);
6548         }
6549 }
6550
6551 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
6552                                     Compose *compose)
6553 {
6554         gtk_stext_set_point(GTK_STEXT(widget),
6555                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6556 }
6557
6558 #if 0
6559 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
6560                                  Compose *compose)
6561 {
6562         gtk_stext_set_point(GTK_STEXT(widget),
6563                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6564 }
6565 #endif
6566
6567 #if 0 /* NEW COMPOSE GUI */
6568 static void compose_toggle_to_cb(gpointer data, guint action,
6569                                  GtkWidget *widget)
6570 {
6571         Compose *compose = (Compose *)data;
6572
6573         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6574                 gtk_widget_show(compose->to_hbox);
6575                 gtk_widget_show(compose->to_entry);
6576                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
6577                 compose->use_to = TRUE;
6578         } else {
6579                 gtk_widget_hide(compose->to_hbox);
6580                 gtk_widget_hide(compose->to_entry);
6581                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
6582                 gtk_widget_queue_resize(compose->table_vbox);
6583                 compose->use_to = FALSE;
6584         }
6585
6586         if (addressbook_get_target_compose() == compose)
6587                 addressbook_set_target_compose(compose);
6588 }
6589
6590 static void compose_toggle_cc_cb(gpointer data, guint action,
6591                                  GtkWidget *widget)
6592 {
6593         Compose *compose = (Compose *)data;
6594
6595         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6596                 gtk_widget_show(compose->cc_hbox);
6597                 gtk_widget_show(compose->cc_entry);
6598                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
6599                 compose->use_cc = TRUE;
6600         } else {
6601                 gtk_widget_hide(compose->cc_hbox);
6602                 gtk_widget_hide(compose->cc_entry);
6603                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
6604                 gtk_widget_queue_resize(compose->table_vbox);
6605                 compose->use_cc = FALSE;
6606         }
6607
6608         if (addressbook_get_target_compose() == compose)
6609                 addressbook_set_target_compose(compose);
6610 }
6611
6612 static void compose_toggle_bcc_cb(gpointer data, guint action,
6613                                   GtkWidget *widget)
6614 {
6615         Compose *compose = (Compose *)data;
6616
6617         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6618                 gtk_widget_show(compose->bcc_hbox);
6619                 gtk_widget_show(compose->bcc_entry);
6620                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
6621                 compose->use_bcc = TRUE;
6622         } else {
6623                 gtk_widget_hide(compose->bcc_hbox);
6624                 gtk_widget_hide(compose->bcc_entry);
6625                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
6626                 gtk_widget_queue_resize(compose->table_vbox);
6627                 compose->use_bcc = FALSE;
6628         }
6629
6630         if (addressbook_get_target_compose() == compose)
6631                 addressbook_set_target_compose(compose);
6632 }
6633
6634 static void compose_toggle_replyto_cb(gpointer data, guint action,
6635                                       GtkWidget *widget)
6636 {
6637         Compose *compose = (Compose *)data;
6638
6639         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6640                 gtk_widget_show(compose->reply_hbox);
6641                 gtk_widget_show(compose->reply_entry);
6642                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
6643                 compose->use_replyto = TRUE;
6644         } else {
6645                 gtk_widget_hide(compose->reply_hbox);
6646                 gtk_widget_hide(compose->reply_entry);
6647                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
6648                 gtk_widget_queue_resize(compose->table_vbox);
6649                 compose->use_replyto = FALSE;
6650         }
6651 }
6652
6653 static void compose_toggle_followupto_cb(gpointer data, guint action,
6654                                          GtkWidget *widget)
6655 {
6656         Compose *compose = (Compose *)data;
6657
6658         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6659                 gtk_widget_show(compose->followup_hbox);
6660                 gtk_widget_show(compose->followup_entry);
6661                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
6662                 compose->use_followupto = TRUE;
6663         } else {
6664                 gtk_widget_hide(compose->followup_hbox);
6665                 gtk_widget_hide(compose->followup_entry);
6666                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
6667                 gtk_widget_queue_resize(compose->table_vbox);
6668                 compose->use_followupto = FALSE;
6669         }
6670 }
6671
6672 static void compose_toggle_attach_cb(gpointer data, guint action,
6673                                      GtkWidget *widget)
6674 {
6675         Compose *compose = (Compose *)data;
6676
6677         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6678                 gtk_widget_ref(compose->edit_vbox);
6679
6680                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6681                                        compose->edit_vbox);
6682                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
6683                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
6684                                    TRUE, TRUE, 0);
6685                 gtk_widget_show(compose->paned);
6686
6687                 gtk_widget_unref(compose->edit_vbox);
6688                 gtk_widget_unref(compose->paned);
6689
6690                 compose->use_attach = TRUE;
6691         } else {
6692                 gtk_widget_ref(compose->paned);
6693                 gtk_widget_ref(compose->edit_vbox);
6694
6695                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6696                                        compose->paned);
6697                 gtkut_container_remove(GTK_CONTAINER(compose->paned),
6698                                        compose->edit_vbox);
6699                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
6700                                    compose->edit_vbox, TRUE, TRUE, 0);
6701
6702                 gtk_widget_unref(compose->edit_vbox);
6703
6704                 compose->use_attach = FALSE;
6705         }
6706 }
6707 #endif
6708
6709 #if USE_GPGME
6710 static void compose_toggle_sign_cb(gpointer data, guint action,
6711                                    GtkWidget *widget)
6712 {
6713         Compose *compose = (Compose *)data;
6714
6715         if (GTK_CHECK_MENU_ITEM(widget)->active)
6716                 compose->use_signing = TRUE;
6717         else
6718                 compose->use_signing = FALSE;
6719
6720         compose_update_gnupg_mode_menu_item(compose);
6721 }
6722
6723 static void compose_toggle_encrypt_cb(gpointer data, guint action,
6724                                       GtkWidget *widget)
6725 {
6726         Compose *compose = (Compose *)data;
6727
6728         if (GTK_CHECK_MENU_ITEM(widget)->active)
6729                 compose->use_encryption = TRUE;
6730         else
6731                 compose->use_encryption = FALSE;
6732                 
6733         compose_update_gnupg_mode_menu_item(compose);
6734 }
6735
6736 static void activate_gnupg_mode (Compose *compose, PrefsAccount *account) 
6737 {
6738         if (account->default_gnupg_mode)
6739                 compose->gnupg_mode = GNUPG_MODE_INLINE;
6740         else
6741                 compose->gnupg_mode = GNUPG_MODE_DETACH;
6742                 
6743         compose_update_gnupg_mode_menu_item(compose);
6744 }
6745 #endif /* USE_GPGME */
6746
6747 static void compose_toggle_ruler_cb(gpointer data, guint action,
6748                                     GtkWidget *widget)
6749 {
6750         Compose *compose = (Compose *)data;
6751
6752         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6753                 gtk_widget_show(compose->ruler_hbox);
6754                 prefs_common.show_ruler = TRUE;
6755         } else {
6756                 gtk_widget_hide(compose->ruler_hbox);
6757                 gtk_widget_queue_resize(compose->edit_vbox);
6758                 prefs_common.show_ruler = FALSE;
6759         }
6760 }
6761
6762 static void compose_attach_drag_received_cb (GtkWidget          *widget,
6763                                              GdkDragContext     *drag_context,
6764                                              gint                x,
6765                                              gint                y,
6766                                              GtkSelectionData   *data,
6767                                              guint               info,
6768                                              guint               time,
6769                                              gpointer            user_data)
6770 {
6771         Compose *compose = (Compose *)user_data;
6772         GList *list, *tmp;
6773
6774         list = uri_list_extract_filenames((const gchar *)data->data);
6775         for (tmp = list; tmp != NULL; tmp = tmp->next)
6776                 compose_attach_append
6777                         (compose, (const gchar *)tmp->data,
6778                          (const gchar *)tmp->data, NULL);
6779         if (list) compose_changed_cb(NULL, compose);
6780         list_free_strings(list);
6781         g_list_free(list);
6782 }
6783
6784 static void compose_insert_drag_received_cb (GtkWidget          *widget,
6785                                              GdkDragContext     *drag_context,
6786                                              gint                x,
6787                                              gint                y,
6788                                              GtkSelectionData   *data,
6789                                              guint               info,
6790                                              guint               time,
6791                                              gpointer            user_data)
6792 {
6793         Compose *compose = (Compose *)user_data;
6794         GList *list, *tmp;
6795
6796         list = uri_list_extract_filenames((const gchar *)data->data);
6797         for (tmp = list; tmp != NULL; tmp = tmp->next)
6798                 compose_insert_file(compose, (const gchar *)tmp->data);
6799         list_free_strings(list);
6800         g_list_free(list);
6801 }
6802
6803 #if 0 /* NEW COMPOSE GUI */
6804 static void to_activated(GtkWidget *widget, Compose *compose)
6805 {
6806         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
6807                 gtk_widget_grab_focus(compose->newsgroups_entry);
6808         else
6809                 gtk_widget_grab_focus(compose->subject_entry);
6810 }
6811
6812 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
6813 {
6814         gtk_widget_grab_focus(compose->subject_entry);
6815 }
6816
6817 static void subject_activated(GtkWidget *widget, Compose *compose)
6818 {
6819         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
6820                 gtk_widget_grab_focus(compose->cc_entry);
6821         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6822                 gtk_widget_grab_focus(compose->bcc_entry);
6823         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6824                 gtk_widget_grab_focus(compose->reply_entry);
6825         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6826                 gtk_widget_grab_focus(compose->followup_entry);
6827         else
6828                 gtk_widget_grab_focus(compose->text);
6829 }
6830
6831 static void cc_activated(GtkWidget *widget, Compose *compose)
6832 {
6833         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6834                 gtk_widget_grab_focus(compose->bcc_entry);
6835         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6836                 gtk_widget_grab_focus(compose->reply_entry);
6837         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6838                 gtk_widget_grab_focus(compose->followup_entry);
6839         else
6840                 gtk_widget_grab_focus(compose->text);
6841 }
6842
6843 static void bcc_activated(GtkWidget *widget, Compose *compose)
6844 {
6845         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6846                 gtk_widget_grab_focus(compose->reply_entry);
6847         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6848                 gtk_widget_grab_focus(compose->followup_entry);
6849         else
6850                 gtk_widget_grab_focus(compose->text);
6851 }
6852
6853 static void replyto_activated(GtkWidget *widget, Compose *compose)
6854 {
6855         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6856                 gtk_widget_grab_focus(compose->followup_entry);
6857         else
6858                 gtk_widget_grab_focus(compose->text);
6859 }
6860
6861 static void followupto_activated(GtkWidget *widget, Compose *compose)
6862 {
6863         gtk_widget_grab_focus(compose->text);
6864 }
6865 #endif
6866
6867 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
6868                                              GtkWidget *widget)
6869 {
6870         Compose *compose = (Compose *)data;
6871
6872         if (GTK_CHECK_MENU_ITEM(widget)->active)
6873                 compose->return_receipt = TRUE;
6874         else
6875                 compose->return_receipt = FALSE;
6876 }
6877
6878 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
6879                                              GtkWidget *widget)
6880 {
6881         Compose *compose = (Compose *)data;
6882
6883         if (GTK_CHECK_MENU_ITEM(widget)->active)
6884                 compose->remove_references = TRUE;
6885         else
6886                 compose->remove_references = FALSE;
6887 }
6888
6889 void compose_headerentry_key_press_event_cb(GtkWidget *entry,
6890                                             GdkEventKey *event,
6891                                             ComposeHeaderEntry *headerentry)
6892 {
6893         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
6894             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
6895             !(event->state & GDK_MODIFIER_MASK) &&
6896             (event->keyval == GDK_BackSpace) &&
6897             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
6898                 gtk_container_remove
6899                         (GTK_CONTAINER(headerentry->compose->header_table),
6900                          headerentry->combo);
6901                 gtk_container_remove
6902                         (GTK_CONTAINER(headerentry->compose->header_table),
6903                          headerentry->entry);
6904                 headerentry->compose->header_list =
6905                         g_slist_remove(headerentry->compose->header_list,
6906                                        headerentry);
6907                 g_free(headerentry);
6908         } else  if (event->keyval == GDK_Tab) {
6909                 if (headerentry->compose->header_last == headerentry) {
6910                         /* Override default next focus, and give it to subject_entry
6911                          * instead of notebook tabs
6912                          */
6913                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry), "key-press-event"); 
6914                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
6915                 }
6916         }
6917
6918 }
6919
6920 void compose_headerentry_changed_cb(GtkWidget *entry,
6921                                     ComposeHeaderEntry *headerentry)
6922 {
6923         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
6924                 headerentry->compose->header_list =
6925                         g_slist_append(headerentry->compose->header_list,
6926                                        headerentry);
6927                 compose_create_header_entry(headerentry->compose);
6928                 gtk_signal_disconnect_by_func
6929                         (GTK_OBJECT(entry),
6930                          GTK_SIGNAL_FUNC(compose_headerentry_changed_cb),
6931                          headerentry);
6932                 /* Automatically scroll down */
6933                 compose_show_first_last_header(headerentry->compose, FALSE);
6934                 
6935         }
6936 }
6937
6938 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
6939 {
6940         GtkAdjustment *vadj;
6941
6942         g_return_if_fail(compose);
6943         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
6944         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
6945
6946         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
6947         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
6948 }
6949
6950 static void text_activated(GtkWidget *widget, Compose *compose)
6951 {
6952         compose_send_control_enter(compose);
6953 }
6954
6955 static void text_inserted(GtkWidget *widget, const gchar *text,
6956                           gint length, gint *position, Compose *compose)
6957 {
6958         GtkEditable *editable = GTK_EDITABLE(widget);
6959         gint paste_as_quotation = GPOINTER_TO_INT(gtk_object_get_data
6960                                 (GTK_OBJECT(widget), "paste_as_quotation"));
6961
6962         gtk_signal_handler_block_by_func(GTK_OBJECT(widget),
6963                                          GTK_SIGNAL_FUNC(text_inserted),
6964                                          compose);
6965         if (paste_as_quotation) {
6966                 gchar *new_text;
6967                 gchar *qmark;
6968                 gint pos;
6969
6970                 new_text = g_strndup(text, length);
6971                 if (prefs_common.quotemark && *prefs_common.quotemark)
6972                         qmark = prefs_common.quotemark;
6973                 else
6974                         qmark = "> ";
6975                 gtk_stext_set_point(GTK_STEXT(widget), *position);
6976                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text);
6977                 pos = gtk_stext_get_point(GTK_STEXT(widget));
6978                 gtk_editable_set_position(editable, pos);
6979                 *position = pos;
6980                 g_free(new_text);
6981                 gtk_object_set_data(GTK_OBJECT(widget), "paste_as_quotation",
6982                                     GINT_TO_POINTER(paste_as_quotation - 1));
6983         } else
6984                 gtk_editable_insert_text(editable, text, length, position);
6985
6986         if (prefs_common.autowrap)
6987                 compose_wrap_line_all_full(compose, TRUE);
6988
6989         gtk_signal_handler_unblock_by_func(GTK_OBJECT(widget),
6990                                            GTK_SIGNAL_FUNC(text_inserted),
6991                                            compose);
6992         gtk_signal_emit_stop_by_name(GTK_OBJECT(editable), "insert_text");
6993
6994         
6995         if (prefs_common.autosave && 
6996             gtk_stext_get_length(GTK_STEXT(widget)) % prefs_common.autosave_length == 0)
6997                 compose_draft_cb((gpointer)compose, 2, NULL);
6998 }
6999
7000 static gboolean compose_send_control_enter(Compose *compose)
7001 {
7002         GdkEvent *ev;
7003         GdkEventKey *kev;
7004         GtkItemFactory *ifactory;
7005         GtkAccelEntry *accel;
7006         GtkWidget *send_menu;
7007         GSList *list;
7008         GdkModifierType ignored_mods =
7009                 (GDK_LOCK_MASK | GDK_MOD2_MASK | GDK_MOD3_MASK |
7010                  GDK_MOD4_MASK | GDK_MOD5_MASK);
7011
7012         ev = gtk_get_current_event();
7013         if (ev->type != GDK_KEY_PRESS) return FALSE;
7014
7015         kev = (GdkEventKey *)ev;
7016         if (!(kev->keyval == GDK_Return && (kev->state & GDK_CONTROL_MASK)))
7017                 return FALSE;
7018
7019         ifactory = gtk_item_factory_from_widget(compose->menubar);
7020         send_menu = gtk_item_factory_get_widget(ifactory, "/Message/Send");
7021         list = gtk_accel_group_entries_from_object(GTK_OBJECT(send_menu));
7022         if (!list)
7023                 return FALSE;
7024
7025         accel = (GtkAccelEntry *)list->data;
7026         if (accel && accel->accelerator_key == kev->keyval &&
7027             (accel->accelerator_mods & ~ignored_mods) ==
7028             (kev->state & ~ignored_mods)) {
7029                 compose_send_cb(compose, 0, NULL);
7030                 return TRUE;
7031         }
7032
7033         return FALSE;
7034 }
7035
7036 #if USE_ASPELL
7037 static void compose_check_all(Compose *compose)
7038 {
7039         if (compose->gtkaspell)
7040                 gtkaspell_check_all(compose->gtkaspell);
7041 }
7042
7043 static void compose_highlight_all(Compose *compose)
7044 {
7045         if (compose->gtkaspell)
7046                 gtkaspell_highlight_all(compose->gtkaspell);
7047 }
7048
7049 static void compose_check_backwards(Compose *compose)
7050 {
7051         if (compose->gtkaspell) 
7052                 gtkaspell_check_backwards(compose->gtkaspell);
7053         else {
7054                 GtkItemFactory *ifactory;
7055                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
7056                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
7057                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
7058         }
7059 }
7060
7061 static void compose_check_forwards_go(Compose *compose)
7062 {
7063         if (compose->gtkaspell) 
7064                 gtkaspell_check_forwards_go(compose->gtkaspell);
7065         else {
7066                 GtkItemFactory *ifactory;
7067                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
7068                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
7069                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
7070         }
7071 }
7072 #endif
7073